【发布时间】:2021-09-01 09:39:33
【问题描述】:
我正在尝试创建一个验证函数,但是当我试图通过将所有内容放入函数中来使代码“更整洁”时,代码停止工作。 这是我的原始代码:
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);
}
这是输出:
这是我尝试从 main 中取出 do while 循环的版本的代码:
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);
}
这是一个不起作用的输出(它在没有给我另一次尝试的情况下终止):
【问题讨论】:
-
do { ... }while (checker==0);this 从不循环,每次第一次迭代后都会返回。if的两条路径都返回一个值,因此它永远不会进入第二次迭代。 -
当您告诉您的程序“返回”时,它会执行此操作,无论该代码周围是否有循环。
-
谢谢@Michael
-
谢谢你@Tom
-
不敢相信我学了 8 个月的 Java 却没有意识到这一点
标签: java if-statement while-loop java.util.scanner do-while