[英]How to loop a user input until integer is entered?
I want to run an interactive program where a user is prompted to enter a number of students.我想运行一个交互式程序,提示用户输入一些学生。 If the user inputs a letter or other character besides a whole number, they should be asked again ("Enter the number of students: ")
如果用户输入除整数以外的字母或其他字符,则应再次询问他们(“输入学生人数:”)
I have the following code:我有以下代码:
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
size = s.nextInt();**
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
How can I create a loop for this?我如何为此创建一个循环?
Let's add a loop, take the value as String and check if it is a number:让我们添加一个循环,将值作为 String 并检查它是否为数字:
String sizeString;
int size;
Scanner s = new Scanner(System.in);
do {
System.out.print("Enter the number of students: ");
sizeString = s.nextLine();
} while (!(sizeString.matches("[0-9]+") && sizeString.length() > 0));
size = Integer.parseInt(sizeString);
try this尝试这个
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
Try catching the exception and handling it until you get the desired input.尝试捕获异常并处理它,直到获得所需的输入。
int numberOfStudents;
while(true)
{
try {
System.out.print("Enter the number of student: ");
numberOfStudents = Integer.parseInt(s.next());
break;
}
catch(NumberFormatException e) {
System.out.println("You have not entered an Integer!");
}
}
//Then assign numberOfStudents to the score array
int scores[] = new int[numberOfStudents]
int no1 = 0;整数 1 = 0;
Scanner scanner = new Scanner(System.in);扫描仪扫描仪=新扫描仪(System.in);
while(true)
{
try {
System.out.print("Number 1: ");
no1 = Integer.parseInt(scanner.next());
break;
}
catch(NumberFormatException e) {
System.out.println("..You have not entered valid value!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.