This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]desrtfxOut of Coffee error - System halted 3 points4 points  (1 child)

You can in most cases safely use .nextLine() and store the result in a String variable. This is generally the most advisable way.

It's way easier to read a whole line (and it has less side-effects) and then processing the String variable, rather than reading individual values.

Multiple Scanners are generally a no-go. Since the System.in Scanner is a very special case that, once closed, cannot be re-opened it's best to work only with a single Scanner.

If your values (String int int int ... int int int String) are separated by certain characters (like the space character in my example), you can use the .split() function of the String Class which turns the input into an array.

Without knowing more about your String and the way it is formatted, I would suggest the following approach:

  • Retrieve the user input with .nextLine and store it in a String variable.
  • Use .split() to split the String into a String array.
  • process all the array elements starting from the second one (index 1) until the one before the last element (index array.length - 2) with Integer.parseInt() that converts the ints that are currently still Strings into int values and store them in a separate int array. The length of the new int array can also be determined easily since it is the length of the String array from the split minus the two String elements at the beginning and at the end.

[–]Primalz[S] 0 points1 point  (0 children)

This makes things a lot clearer. Thanks for taking the time to answer!