0

I want to make a scanner that scans 10 numbers in a String separated by a space. Such as this:

3 4 5 12 32 32 23 54 65 67. Then I want to parse each numbers into int, and store each number in a int array. Does anyone know how to do this? Thanks.

    String numbers;
    int num[] = new num[10];
    Scanner scan = new Scanner(System.in);

    System.out.println("Type something.");
    numbers = scan.nextLine();
4
  • Hmmm. And what if you want to do it by commas and not spaces? or periods? or question marks. I think split is a much better method as it gives you more options. Commented Mar 23, 2015 at 19:22
  • I tried your code. Types in a line and nothing happens. Commented Mar 23, 2015 at 19:26
  • lol. Did you actually tested the codes yourself? All i got from the outputs are: num0 num0 num0 num0 num0 num0 num0 num0 num0 num0 Commented Mar 23, 2015 at 19:49
  • Idea is to give a gist of the fact that scanner has functionality to use delimiter. Have corrected for u again Commented Mar 23, 2015 at 19:56

2 Answers 2

1

If the numbers are on the same line you can use the split function to create an array of strings and then cast them to int.

String[] numbersSplit = numbers.split();

for(int i = 0; i < numbersSplit.length; i++) {
    num[i] = Integer.parseInt(numbersSplit[i]);
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. It works. But how do you say 1 or more spaces in java?
you can always add a regex to the split function refer to this documentation : docs.oracle.com/javase/7/docs/api/java/lang/…
well you don't have to use split. Scanner does not automatically for you
I learn better by examples. Can you give me an example of using a regex to split it by whitespaces, or commas?
for white spaces you can use .split("\\s+"); and for comas you can use .split(",");
|
1

Scanner by default uses whitespace as delimiter. so you can try the below.Added a system out just to prove the theory.

public static void main(String[] args) {
    int num[] = new int[10];
    Scanner scan = new Scanner(System.in);
    int i = 0;
    while (scan.hasNext("\\d+")) {
        num[i] = scan.nextInt();
        i++;
    }
    for (int j = 0; j < num.length; j++) {
        System.out.println("num" + num[j]);
    }

}

If you have delimiter other than space, use syntax like this.

Scanner scan = new Scanner(System.in).useDelimiter(pattern);

PS: press any character to escape from loop.

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.