Maharsh Mangal
Maharsh Mangal

Reputation: 27

Can't use scanner for string and integer at the same time

I'm working on this code which takes an integer as a test case then takes a string and an integer for each test case But I keep getting this exception:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at OverSizedPancakeFlipper.main(OverSizedPancakeFlipper.java:18)

My code basically looks like this:

Scanner userInput = new Scanner(System.in);
int T=userInput.nextInt();

userInput.nextLine();
while(T-->0){
    String S=userInput.nextLine();
    char[] ch = S.toCharArray();
    int K=userInput.nextInt();
    //code does work here
}

Do let me know if you need any other information and thanks for all the help.

Upvotes: 0

Views: 8698

Answers (3)

Linan
Linan

Reputation: 1

Change your code to

while(variableName==0){
  ...
}

when writing a while loop: you want to make sure that the loop will stop at current point, so it won't go forever.

Upvotes: 0

Patrick Parker
Patrick Parker

Reputation: 4959

Change this line:

int K=userInput.nextInt();

To this:

int K=Integer.parseInt(userInput.nextLine());

Of course you will need to handle NumberFormatException.

For an explanation of this change, see duplicate question Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

In short, the problem is that you forgot to read the newline after the integer. So then nextLine will take the empty string and consume the newline. Then nextInt will fail because it is positioned at invalid content.

Upvotes: 1

Avreen
Avreen

Reputation: 19

Scanner userInput = new Scanner(System.in);

do{
    String s=userInput.nextLine();
    char[] ch = s.toCharArray();
    int k=userInput.nextInt();
     //code does work here
}while(k==0);

you can use this.....

Upvotes: 0

Related Questions