-1

I'm really new to coding and right now I need to take an input from the user in one line seperated by spaces for example "0 1 2" and then take the ints in that string and place them in separate int variables.

This is what I have so far:

Scanner scan = new Scanner(System.in); //takes input from user
input = scan.nextLine();
Scanner intValues = new Scanner(input); //takes input from the "input" variable

then I go to place the first int value into a variable and get a "NoSuchElementException"

int x = intValues.nextInt();

What am I doing wrong here? Also I'm not allowed to use arrays for this assignment.

2 Answers2

1

There is no need to use 2 scanner to read the input. You can even achieve this using one scanner. Like this:

Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
int z = scanner.nextInt();
Jayesh Doolani
  • 1,233
  • 10
  • 13
1

You should always use hasNext method on the Scanner class to avoid the NoSuchelementException exception.

Try the following snippet:

    Scanner scan = new Scanner(System.in); //takes input from user
    String input = scan.nextLine();
    Scanner intValues = new Scanner(input); 
    while(intValues.hasNextInt()) {
        int x = intValues.nextInt();
        System.out.println(x);
    }

Or try the following which uses only one scanner:

    Scanner scan = new Scanner(System.in); //takes input from user
    while(scan.hasNextInt()) {
        int x = scan.nextInt();
        System.out.println(x);
    }
VHS
  • 9,534
  • 3
  • 19
  • 43
  • I think what you are doing wont work for the case with `0 1 2` and then pressing enter… – Luatic Mar 14 '17 at 20:05
  • 2
    better to use hasNextInt here – Patrick Parker Mar 14 '17 at 20:08
  • @PatrickParker, that's an excellent suggestion. I edited my answer accordingly. thanks much. – VHS Mar 14 '17 at 20:14
  • Thank you for this answer, but the problem i'm having is that the intValues.nextInt isn't giving me any int values from the string DESPITE the string being literally "0 1 2". The while statement is never true in this case and nothing gets put into x, which is a huge problem for the rest of my code. – Mohd Hasan Mar 14 '17 at 20:23
  • @MohdHasan, what is your actual input? is it `0 1 2`? – VHS Mar 14 '17 at 20:30
  • Yes, the actual input im using to test out my code is "0 1 2", which is put into variable "input" I'm trying to put each of the int values, 0 1 and 2 into separate int variables, but i'm running into the issue as I stated above when I try to use a second scanner to get the 3 int values in this string. I understand that this could be done with just one scanner object but the exercise i'm doing wants me to do it this way... – Mohd Hasan Mar 14 '17 at 20:39
  • @MohdHasan, you need to show your code in that case. I have shown two choices in my answer. Both work fine. – VHS Mar 14 '17 at 20:42