为什么我的验证函数不起作用(用于验证用户输入是否为范围内的整数)

Why is my validation function not working (to validate if user input is an integer within range)

提问人:kai 提问时间:6/16/2021 最后编辑:Tomkai 更新时间:6/16/2021 访问量:190

问:

我正在尝试制作一个验证函数,但是当我试图通过将所有内容放入函数中来使代码“更整洁”时,代码停止工作。 这是我的原始代码:

static int readValidInt(Scanner in, String prompt, int min,  int max){
    while(!in.hasNextInt()) { //Makes sure that user inputs an Integer, not String, double, etc
        System.out.println("Sorry, only numbers in integer form is allowed. Please enter your choice as an integer between 1 and 4");
        in.next();
    }
    int a = in.nextInt();
    if ( a >= min && a <= max) {
        System.out.println("you have chosen board"+ a );
        return a;   
    }
    else {
        System.out.println(prompt);
        return 0;
    }
    //in main, use a do while loop to keep this running until the input is right(until a becomes something that is not 0)
}

public static void main (String args[]) {
    int validinput;
    Scanner input = new Scanner(System.in);
    System.out.println("WELCOME TO CS300 PEG SOLITAIR GAME !" + "\n====================================");
    System.out.println("Board Style Menu");
    System.out.println("\t1) Cross \n \t2) Circle \n \t3) Triangle \n\t3) Simple T"); //Prints out the 4 options of boards, spacing all of them with \t and \n
    System.out.println("Choose a board style");
    do {
        validinput = readValidInt(input, "Bruh that's not valid", 1, 4);
    }
    while (validinput == 0);
}

这是输出:https://i.stack.imgur.com/DpQEE.png

这是我试图将 do while 循环从 main 中取出的版本代码:

public static int readValidInt(Scanner in, String prompt, int min,  int max){   
    int checker;
    int a;

    while(!in.hasNextInt()) { //Makes sure that user inputs an Integer, not String, double, etc
        System.out.println("Sorry, only numbers in integer form is allowed. Please enter your choice as an integer between 1 and 4");
        in.next();
    }
    do {
         a = in.nextInt();
            if ( a >= min && a <= max) {
                    System.out.println("you have chosen board"+ a );
                    checker = 1;
                    return a;   

                }
        else {
            System.out.println(prompt);
            checker = 0;
            return 0;
        }   
    }while (checker==0);
}

public static void main (String args[]) {
    
    Scanner input = new Scanner(System.in);
    System.out.println("WELCOME TO CS300 PEG SOLITssssAIR GAME !" + "\n====================================");
    System.out.println("Board Style Menu");
    System.out.println("\t1) Cross \n \t2) Circle \n \t3) Triangle \n\t4) Simple T"); //Prints out the 4 options of boards, spacing all of them with \t and \n
    System.out.println("Choose a board style");
    
    readValidInt(input, "Bruh that's not valid", 1, 4);
}

这是不起作用的输出(它终止而没有给我另一次尝试):https://i.stack.imgur.com/flOXj.png

java if-statement while-loop java.util.scanner do-while

评论

0赞 Michael 6/16/2021
do { ... }while (checker==0);这从不循环,每次都会在第一次迭代后返回。两条路径都返回一个值,因此它永远不会到达第二次迭代。if
0赞 Tom 6/16/2021
当你告诉你的程序“返回”时,它就会这样做,无论是否有围绕该代码的循环。
0赞 kai 6/16/2021
简直不敢相信我学会了 8 个月的 Java 却没有意识到这一点
0赞 kai 6/16/2021
在我修复 do-while 后,我刚刚发现了这个程序的另一个缺陷,并希望你们能帮助我:如果我输入 345,程序会说不允许这个数字,因为它不在 1 到 4 之间,但由于它是一个整数,它已经通过了 while(!in.hasNextInt()) 循环, 这意味着如果我在第一次尝试 345 输入 String/double,它就会成为异常。有没有办法防止这种情况发生?我正在考虑将 while 循环放在 do 块中(这在我的大脑中是有道理的,但这只会成为另一个 do while 循环)
0赞 kai 6/16/2021
我尽量避免使用 try catch,这样函数就不会太笨拙

答:

0赞 Nexevis 6/16/2021 #1

问题出在你的分支中,无论如何,你总是(将退出方法)在第一次循环迭代中。你永远不会循环。if-elsereturn

若要解决此问题,需要将值设置为循环之前和之后尝试的值:checkerreturnreturn checker

public static int readValidInt(Scanner in, String prompt, int min, int max) {
    int checker;
    int a;

    while (!in.hasNextInt()) { // Makes sure that user inputs an Integer, not String, double, etc
        System.out.println(
                "Sorry, only numbers in integer form is allowed. Please enter your choice as an integer between 1 and 4");
        in.next();
    }
    do {
        a = in.nextInt();
        if (a >= min && a <= max) {
            System.out.println("you have chosen board" + a);
            checker = a;

        } else {
            System.out.println(prompt);
            checker = 0;
        }
    } while (checker == 0);
    
    return checker;
}

输出:

Choose a board style
five
Sorry, only numbers in integer form is allowed. Please enter your choice as an integer between 1 and 4
5
Bruh that's not valid
1
you have chosen board1