1

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).

2 Answers 2

3

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];
}
Sign up to request clarification or add additional context in comments.

5 Comments

Yup, and probably add a check to see if the length is OK. if (salespersons.length < 2 || salespersons.length > 4) { show error }.
Thanks, one more question though. How would I use the values outside the for statement, for instance, determining the length then using the correct indexes?
String sales1 = salespersons[0], and use a guard for 3-4 so you don't get IndexOutOfBounds String sales4 = salespersons.length>=4 ? salespersons[3] : null;, but I'd avoid hardcoding those - you might look for a way to get a collection of all pairs from an array.
How would I go about doing that? I'm sorry, I am really new to Java and don't know a lot about it..
You mean the pairs solution? It would be best to ask a new question, after seeing if you can find it on your own (maybe stackoverflow.com/q/2392652/154066 ?) - it's hard to provide a good answer in comments.
0

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];
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.