【问题标题】:Can't use scanner for string and integer at the same time不能同时对字符串和整数使用扫描仪
【发布时间】:2017-04-08 13:39:34
【问题描述】:

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

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
}

如果您需要任何其他信息,请告诉我,感谢您提供的所有帮助。

【问题讨论】:

  • 输入是什么?
  • @BackSlash 输入的第一行给出了测试用例的数量,T.T 测试用例紧随其后。每行由一个字符串 S 和一个整数 K 组成。该字符串由一系列 + 和 - 符号组成。
  • 我的意思是,您提供什么作为输入?向我们提供演示问题的示例数据,以便我们告诉您发生了什么

标签: java arrays eclipse exception-handling inputmismatchexception


【解决方案1】:

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

你可以用这个.....

【讨论】:

  • 没有解决我的问题..你能解释一下你为什么决定做一个 do while 循环吗?
  • 所以,基本上它会在 k=0 时提示您输入字符串;它让您有机会在检查进一步条件之前输入字符串
【解决方案2】:

改变这一行:

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 会失败,因为它定位在无效的内容上。

【讨论】:

  • 为了避免这种行为,你应该在nextInt()之前调用userInput.nextLine()。无需自己解析 int,只需忽略一行,正如您链接的答案所暗示的那样。
  • @BackSlash 我知道有多种方法可以解决它,是的。但是链接的答案说“这样做会更好”。附言按照你的建议在 nextInt 之前调用 nextLine 是行不通的。相反,您需要在 nextInt 之后调用它。就我个人而言,这对我来说似乎有点骇人听闻。您可能会忽略整数后面的行上的数据。
【解决方案3】:

把你的代码改成

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

在编写while 循环时:您要确保循环将在当前点停止,因此它不会永远

【讨论】:

  • 格式化您的代码,以便更容易查看文本和代码 sn-p。
猜你喜欢
  • 1970-01-01
  • 2014-07-01
  • 2021-03-06
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多