繁体   English   中英

如何让程序要求用户输入,直到他们给出有效响应?

[英]How to make the program ask the user for input until they give a valid response?

你能帮我制作这个程序以获得正确的号码吗? 程序应该检查输入类型,它应该是 int。 此外,程序应检查该值是否在 1 到 10 之间。如果这些条件为真,则应将该值分配给 correctNumber。 到目前为止,我想出了这段代码,但我很难让它正常工作。

System.out.println("Enter a number from 1 to 10:");
    Scanner scanner = new Scanner(System.in);
    while (!scanner.hasNextInt() || !isCorrectNumber(scanner.nextInt())) {
                System.out.println("Incorrect input!");
                scanner.next();
            }
            int correctNumber = scanner.nextInt();
    
        }
    private static boolean isCorrectNumber(int n) {
        return size >= 1 && size <= 10;
    }

您在 while 条件下要求输入 2 次 使用变量保存输入,然后使用该变量

public static void main(String[] args) throws IOException {
    
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    
    String x = input.readLine();
    while (!isInt(x)) {
        x = input.readLine();
    }
    System.out.println(x);
}

我要求输入,我得到一个字符串,现在我必须检查这个字符串是否可以是一个数字。 为此,我创建了一个 boolean function isInt(String) 获取字符串,如果它可以是数字则返回。

public static boolean isInt(String str) {//function that checks if String can be parsed into an integer
    try {
        Integer.parseInt(str);
        return true;
    }catch (NumberFormatException e) {
        return false;
    }
}

我希望我有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM