我正在编写这段代码,它采用一个整数作为测试用例,然后为每个测试用例采用一个字符串和一个整数 但我不断收到此异常:
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
}
如果您需要任何其他信息,请告诉我,感谢您的帮助。
最佳答案
更改此行:
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 将失败,因为它定位在无效内容处。
关于java - 不能同时使用字符串和整数扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43294827/