Reputation: 1202
I'm trying to figure out how to read multiple entries from the Scanner class in Java. I need to get the name of each person entered and then compare the total amounts to each entry.
Here is my code:
String[] salespersons = new String[3];
System.out.println("Please enter at least two salespeople but no more than four, to compare sales against: ");
// use scanner class to read input from the user
Scanner input = new Scanner(System.in);
String line = input.nextLine();
String[] values = line.split(",");
for (String s: values) {
salespersons = values;
}
For some reasons, I can't get the values that are placed in salespersons. (I am really new to Java, sorry if my question does not make a lot of sense).
Upvotes: 1
Views: 1484
Reputation: 11710
You can just write:
salespersons = line.split(",");
You don't need to assign it to an intermediary values variable, and then loop over it to assign it to salespersons. But if you did want to do that, you should use an indexed for loop:
for (int i = 0; i<Math.min(salespersons.length,values.length); i++) {
salespersons[i] = values[i];
}
Upvotes: 3
Reputation: 1454
When you work with arrays and you want to access them by their index value then you can't make use of enhanced for loops.
The way you want to work is:
String[] salespersons = new String[3];
...
for (int i = 0; i < values.size(); i++){
salespersons[i] = values[i];
}
Upvotes: 0