java - 不能同时使用字符串和整数扫描器

标签 java arrays eclipse exception inputmismatchexception

我正在编写这段代码,它采用一个整数作为测试用例,然后为每个测试用例采用一个字符串和一个整数 但我不断收到此异常:

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/

相关文章:

java - Main(args) 包含多个数组

JAVA 赋值和运算符

javascript - obj.key=value 和 obj.set(key, value) 之间的区别?

java - 在 Eclipse 中将项目转换为 Gradle 后无法运行 JUnit 测试用例

java - 使用批量数据设计独立于数据源的应用程序

java - 如何在没有标签的情况下获取微调值

将 Swift 字符串数组转换为 c 字符**

java - 把txt文件放在eclipse,android的哪里?

android - 如何在eclipse中添加过滤器

java - Java 方法引用稳定吗?