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?

Ankit Rathore
  • 78
  • 1
  • 10
  • 3
    Take a look at http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods for the explanation. – Codebender Aug 25 '15 at 06: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? – hermit Aug 25 '15 at 06: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. – Codebender Aug 25 '15 at 07:04
  • @Codebender I thought trying to parse the newline character into integer value would throw an exception. – hermit Aug 25 '15 at 07:06

2 Answers2

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
   .
   .
   .
}
moffeltje
  • 4,095
  • 4
  • 24
  • 49
1

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();
   .
   .
   .
}
Shah Rukh Qasim
  • 172
  • 1
  • 6
  • 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 Aug 25 '15 at 06:50
  • @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. – Codebender Aug 25 '15 at 07:06
  • 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. – Codebender Aug 25 '15 at 07:09