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

42,108

Solution 1

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.

Solution 2

String integers = "54 65 74";
List<Integer> list = new ArrayList<Integer>();
for (String s : integers.split("\\s"))  
{  
   list.add(Integer.parseInt(s));  
}
list.toArray();

Solution 3

This would be a easier way to do the same -

System.out.println("Enter the elements seperated by spaces: ");
String input = sc.nextLine();
String[] split = input.split("\\s+");
int[] desiredOP = new int[split.length];
int i=0;
for (String string : split) {
    desiredOP[i++] = Integer.parseInt(string);
}

Solution 4

There are alternate ways to achieve the same. but when i tried your code, it seems to work properly.

StringTokenizer strToken = new StringTokenizer("a b c");
int count = strToken.countTokens();
System.out.println(count);

It prints count as 3. default demiliter is " "

I dont know how are you getting your input field. May be it is not returning the complete input in string format.

I think you are using java.util.Scanner for reading your input

java doc from scanner.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

Hence the input is returning just one Integer and leaving the rest unattended

Read this. Scanner#next(), You should use Scanner#nextLine() instead

Share:
42,108
Samuel French
Author by

Samuel French

Updated on January 09, 2020

Comments

  • Samuel French
    Samuel French over 4 years

    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?

  • Ilya
    Ilya over 11 years
    @dystroy i proposed equals and easiest code. I answered on Would it be better to do this a different way?
  • Denys Séguret
    Denys Séguret over 11 years
    Yes but your initial code was totally flawed (now fixed). I don't get who could upvote it, apart people coming just to check there was "split" somewhere in the answer...
  • jlordo
    jlordo over 11 years
    String input = sc.next(); will only read the next token, so the code will have the same problem like OP.
  • Denys Séguret
    Denys Séguret over 11 years
    And in fact it doesn't fix the real problem, seen by jlordo.
  • Subhrajyoti Majumder
    Subhrajyoti Majumder over 11 years
    @jlordo - Thank you very much for your comment. I have updated my code. Please check.
  • Denys Séguret
    Denys Séguret over 11 years
    +1 for the right explanation. Rest of OP's code could be better but is mostly fine.
  • Samuel French
    Samuel French over 11 years
    Ok, so I have done this, but the problem is for some reason the scanner doesn't wait for user input with the sc.nextLine() command it just skips to the next user input
  • Samuel French
    Samuel French over 11 years
    OK, this sounds really noobish, but the reason I had it set as next is because for some reason when I enter sc.nextLine() it just skips the user input and continues on with the program. This is really weird...
  • jlordo
    jlordo over 11 years
    @SamFrench: copied your code, ran it with nextLine(); and worked fine. Try again, if the problem persists, you may have/had a mistake somewhere else.