Java – how to read an integer separated by spaces into an array

There's a problem with my project because I can't get the correct start, reading integer rows separated by user spaces and putting 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. It seems that it just reads the first element in the array, because when initializing count, it is set to 1 for some reason

Who can help me? Would it be better to do it differently?

Solution

Just make a few minor changes to make the code work properly The error is on this line:

String input = sc.next();

As I pointed out in my comment on this issue, it only reads the next tag entered See documentation

If you replace it with it

String input = sc.nextLine();

It will do what you want because nextline () consumes the entire line of input

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>