How do I print a Single item on a Array List
-
21-12-2019 - |
Question
So I want to system print one of the names on my array list I was thinking it's like System.out.print(Names[1]) for the second item on my array list?
System.out.println("How Many Employees On your Payroll");
Employees = reader.nextDouble();
ArrayList Names = new ArrayList();
for (int i=1;i<=Employees;i++)
{
System.out.println("What is the name for Employee #"+i+"");
String userName = userInputScanner.nextLine();
Names.add(userName);
}
System.out.println("Do these Names Seem Correct?: " + Names);
Solution
First of all try to obey Java code conventions: http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367
And to get the second element of the list use
names.get(1);
Where names
is your list.
OTHER TIPS
The JavaDoc is your friend. Use ArrayList#get(int index)
.
First, ArrayList is a generic type so it's better to use ArrayList , for example:
ArrayList<String> Names = new ArrayLis<String> ();
Second,You can access the i'th number of an ArrayList (Say Names) by "get(int index)" method:
Names.get(1)//to get the second items
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow