Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to read integers separated by a space into an array

I am having trouble with my project because I can't get the beginning correct, which is to read a line of integers separated by a space from the user and place the values into an array.

    System.out.println("Enter the elements separated by spaces: ");
    String input = sc.next();
    StringTokenizer strToken = new StringTokenizer(input);
    int count = strToken.countTokens();
    //Reads in the numbers to the array
    System.out.println("Count: " + count);
    int[] arr = new int[count];

    for(int x = 0;x < count;x++){
        arr[x] = Integer.parseInt((String)strToken.nextElement());
    }

This is what I have, and it only seems to read the first element in the array because when count is initialized, it is set to 1 for some reason.

Can anyone help me? Would it be better to do this a different way?

like image 329
Samuel French Avatar asked Jan 15 '13 08:01

Samuel French


People also ask

How do you read space separated integers in Java?

You can use the data. split("\\s+"); function in java to get all the elements in a single line in a String array and then put these elements into the inner ArrayList of the ArrayList of ArrayLists. and for the next line you can move to the next element of the outer ArrayList and so on.

How do you take space separated integer inputs?

To take space-separated integers from user input:Use the input() function to take multiple, space-separated integers. Use the str. split() function to split the string into a list. Use the int() class to convert each string in the list to an integer.


2 Answers

There is only a tiny change necessary to make your code work. The error is in this line:

String input = sc.next();

As pointed out in my comment under the question, it only reads the next token of input. See the documentation.

If you replace it with

String input = sc.nextLine();

it will do what you want it to do, because nextLine() consumes the whole line of input.

like image 51
jlordo Avatar answered Sep 19 '22 23:09

jlordo


String integers = "54 65 74";
List<Integer> list = new ArrayList<Integer>();
for (String s : integers.split("\\s"))  
{  
   list.add(Integer.parseInt(s));  
}
list.toArray();
like image 33
Ilya Avatar answered Sep 22 '22 23:09

Ilya