2015-08-25 58 views
0

我试图做到这一点:错误采取输入字符串整数之后在java中

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

当我编译它显示了一些错误java.util.Scanner.nextInt(Scanner.java:2117)。 最初我认为这是nextLine()的问题,所以我使用next()。后来我发现,如果我走输入的N即

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

然后它好工作之后添加myScanner.nextLine()。我想知道为什么会发生这种情况?

+3

在http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo看看 - 方法的解释。 – Codebender

+0

@Codebender我访问了上面的链接。在解决方案中,异常处理是在使用Integer.parseInt()时完成的,但是当我使用parseInt时,它不会抛出任何异常。为什么这样? – hermit

+0

@hermit,只有在无法解析的情况下才会抛出NumberFormatException异常。但是'NumberFormatExcetion'是一个** unchecked **(扩展的RuntimeException)异常,因此您不必明确地写入抛出或处理它(尽管如果您不抛出它将抛出)。希望这是明确的。 – Codebender

回答

2

需要消耗经过整数,当你进入换行符:

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 
    . 
    . 
    . 
} 
1

有一个换行符离开流。通过@moffeltje使用代码或可能尝试这个办法:

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

如果您要使用此方法,则必须处理NumberFormatException,因为parseInt会尝试将换行符解析为整数值 – hermit

+0

@hermit,'Scanner.nextLine()'将**消耗**新行字符,但它不会被返回给调用者。所以换行符不会被解析。 – Codebender

+0

@Codebender谢谢,解决了混淆 – hermit