0

I was trying to do this :

int n = myScanner.nextInt();
for(int i=0;i<n;i++){
   String str = myScanner.nextLine();
   .
   .
   .
}

when i compiled it shows some errors java.util.Scanner.nextInt(Scanner.java:2117). initially i thought it is a problem of nextLine() so i used next() . then i found out if i add myScanner.nextLine() after taking input in n i.e

    int n = myScanner.nextInt();
    myScanner.nextLine();

Then it worked fine. I want to know why this happened?

4
  • 3
    Take a look at stackoverflow.com/questions/13102045/… for the explanation. Commented Aug 25, 2015 at 6:36
  • @Codebender I visited the above link. In the solution,exception handling is done while using Integer.parseInt(), But when I used parseInt, it does not throw any exception. why is it so? Commented Aug 25, 2015 at 6:58
  • @hermit, a NumberFormatException will be thrown only if it cannot be parsed. But a NumberFormatExcetion is an unchecked (extending RuntimeException) exception, so you don't have to explicitely write throws or handle it (though it will be thrown up if you dont). Hope that's clear. Commented Aug 25, 2015 at 7:04
  • @Codebender I thought trying to parse the newline character into integer value would throw an exception. Commented Aug 25, 2015 at 7:06

2 Answers 2

3

You need to consume the newline character you enter when passing the integer:

int n = myScanner.nextInt(); //gets only integers, no newline
myScanner.nextLine(); //reads the newline
String str;
for(int i=0;i<n;i++){
   str = myScanner.nextLine(); //reads the next input with newline
   .
   .
   .
}
Sign up to request clarification or add additional context in comments.

Comments

2

There is a newline character left in the stream. Use the code by @moffeltje or probably try this:

int n = Integer.parseInt(myScanner.nextLine());
for(int i=0;i<n;i++){
   String str = myScanner.nextLine();
   .
   .
   .
}

3 Comments

You have to handle the NumberFormatException if you are going to use this method because the parseInt will try to parse the newline character into a integer value
@hermit, Scanner.nextLine() will consume the new line character, but it wont be returned to the caller. So the newline character is not going to be parsed.
From the Scanner java doc, This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

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.