-1

我正在处理这个代码,它需要一个整数作为测试用例,然后每个测试用例需要一个字符串和一个整数 但我不断收到此异常:不能同时使用扫描器的字符串和整数

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) 

我的代码基本上是这样的:

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 
} 

不要让我知道,如果你需要的所有帮助的任何其他信息和感谢。

+0

什么是输入? – BackSlash

+0

@BackSlash输入的第一行给出了测试用例的数量,T测试用例如下。每一行由一个字符串S和一个整数K组成。字符串由一系列+和 - 符号组成。 –

+0

我的意思是,你提供什么作为输入? – BackSlash

回答

0

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); 

你可以使用这个.....

+0

没有解决我的问题..你可以解释你为什么决定去一个做while循环? –

+0

所以,基本上它会提示你输入字符串,而k = 0;它让你有机会在检查进一步的条件之前输入字符串 – Avreen

0

while循环时更改您的代码

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

:要确保循环将停止在当前点,所以它永远不会去

+0

格式化你的代码,以便更容易看到文本和代码片段。 –

0

改变这一行:

int K=userInput.nextInt(); 

要这样:

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

当然,你将需要处理NumberFormatException的。

对于这种变化的解释,看到重复的问题Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

总之,问题是,你忘了阅读整数之后的换行符。那么nextLine将会使用空字符串并使用换行符。然后nextInt将失败,因为它位于无效内容。

+0

为了避免这种行为,应该在'nextInt()'之前调用'userInput.nextLine()'。不需要自己解析int,只需忽略一条线,因为您链接的答案也是如此。 – BackSlash

+0

@BackSlash我知道有多种方法可以解决它,是的。但相关答案表示“这样做会更好”。附:在nextInt之前调用nextLine,因为您建议不起作用。相反,你需要在nextInt之后调用它。就我个人而言,这似乎有点ha to。您可能会忽略该整数后面的行上的数据。 –