Java中用户输入值后的循环
public static void main(String args[])throws IOException{
validNumbers = new int[200];
Scanner sc1 = new Scanner(new File("validNumbers.txt"));
int i = 0;
while(sc1.hasNextInt()) {
validNumbers[i++] = sc1.nextInt();
}
// Creating loop for what the user enters
boolean newValidator = true;
Scanner scanner = new Scanner(System.in);
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
// If found, the calculations will get displayed
if(validator(num)) {
System.out.print("The calculated value to this account is: " + calculator(num));
newValidator = false;
System.out.println("\n" + "Would you like to enter another account number? (y/n)");
String ans = "";
ans = scanner.nextLine();
// Needed the false, if not the code would keep asking to "Enter account number: "
if (ans.equals("y")) {
System.out.print("Enter the account number: ");
String num2 = scanner.nextLine();
System.out.print("The calculated value to this account is: " + calculator(num2));
} else if(ans.equals("n")) {
newValidator = false;
System.out.println("** Program Exit **");
}
}
// Wanted to add a loop for the user to decide if they want to continue iff wrong account is inputed
else {
System.out.println("Not valid account number" + "\n\n" + "Would you like to try again? (y/n)");
String ans = "";
ans = scanner.nextLine();
if(ans.equals("y")) {
newValidator = true;
}
// How the program terminates if the user does not wish to continue
else if(ans.equals("n")) {
newValidator = false;
System.out.println("Not valid input, the program is now terminated!");
}
}
}
}
}
(使用Java)代码执行以下操作: 1.)当用户输入正确的数字时,会看到该数字(在文件中)并添加数字 2.)当它不在文件中时,它知道号码不在那里,并告诉用户再试一次,如果用户不想,它将结束程序强> *****(使用Java)代码没有做什么: 1.)在用户输入正确的代码后,程序将询问用户是否要输入另一个帐户(如果是,则添加一个帐户)。这就是我的问题所在,循环在第二次运行后结束,我需要它继续询问他们是否想要输入用户想要退出的另一个帐号单元*****
# 1 楼答案
不需要有嵌套的问题询问另一个帐号,while循环本身将在重复时再次询问用户
只需询问用户是否要输入另一个,如果不想输入,则退出循环。当“newValidator”设置为false时,while循环将退出: