所以这段代码要求输入一个名字和数字1-20,但是如果你输入的数字超过20或者低于1,程序仍会运行,我知道我需要一个条件语句来计算&#的数量34; ANO"停止并重新询问该声明并重新运行该段,但我不知道如何将其实现到代码中。
// library - for interactive input
import java.util.Scanner;
//---------------------------------
// program name header
public class feb24a
{
//--------FUNCTION CODING ---------------
// FUNCTION HEADER
public static void seeit(String msg, String aname, int ano)
{
// statement to accomplish the task of this function
System.out.print("\n The message is " + msg + "\t" + "Name is:" + aname + "\t" + "number is: " + ano);
// return statement without a variable name because it is a void
return;
}
//------------------- MAIN MODULE CODING TO CALL FUNCTIONS ----------------
// Main module header
public static void main (String[] args)
{
String msg, aname;
int ano, again, a, b;
msg = "Hello";
a = 1;
b = 20;
//Loop control variable
again = 2;
while(again == 2)
{
System.out.print("\n enter NAME: ");
Scanner username = new Scanner(System.in);
aname = username.nextLine();
System.out.print("\n enter number 1-20: ");
Scanner userno = new Scanner(System.in);
ano = userno.nextInt();
seeit(msg, aname, ano);
//ask user if they want to do it again, 2 for yes any other for no
System.out.print("\n do you want to do this again? 2 for yes ");
Scanner useragain = new Scanner(System.in);
again = useragain.nextInt();
} //terminate the while loop
}
}

答案 0 :(得分:0)
尝试在while循环中包围ano = userno.nextInt()。 (即,while(ano< 1 || ano> 20))并在while循环中放入提示。这样,它将继续读取一个新的数字,直到它最终不再满足while循环并且将会爆发。
答案 1 :(得分:0)
用这个替换你的while循环:
Scanner scanner = new Scanner(System.in);
while (again == 2) {
ano = 0;
System.out.print("\n enter NAME: ");
aname = scanner.nextLine();
while (ano < 1 || ano > 20) {
System.out.print("\n enter number 1-20: ");
ano = scanner.nextInt();
}
seeit(msg, aname, ano);
System.out.print("\n do you want to do this again? 2 for yes ");
again = scanner.nextInt();
}