gpt4 book ai didi

java - 我的循环进入无限循环。我该如何解决?我不能在第二个循环中输入

转载 作者:行者123 更新时间:2023-12-04 02:28:26 24 4
gpt4 key购买 nike

import java.util.InputMismatchException;
import java.util.Scanner;

public class h {

/** Test Function.
* @param args Kommandozeilenparameter
*/
public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
int input;
boolean check = false;
do {
try {
System.out.println("give me a number: ");

input = scan.nextInt();

check = true;
} catch (InputMismatchException e) {
System.out.println("Eingabe ist falsch");
}
} while (!check);
System.out.println("getout");
}
}
我正在尝试检查用户是否提供整数作为输入。
我试图在 try catch 和 do while 循环的帮助下捕获它。
但它会进入一个无限循环。
我该如何解决?
第二次我不能写任何东西。

最佳答案

来自 javadoc :

Scans the next token of the input as an int. This method will throwInputMismatchException if the next token cannot be translated into avalid int value as described below. If the translation is successful,the scanner advances past the input that matched.


这意味着输入只有在类型正确时才被“读取”。由于您的输入不正确,它不会被读取,下次扫描仪将尝试读取相同的序列 - 导致无限循环。
要解决此问题,请在 catch 块中添加 scan.nextLine()(或其他读取方法)。当我添加 nextLine() 时,它​​对我有用。
你的 catch 块:
catch (InputMismatchException e) {
System.out.println("Eingabe ist falsch");
scan.nextLine();
}

关于java - 我的循环进入无限循环。我该如何解决?我不能在第二个循环中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65781630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com