检查输入是否为正数
checking input for positive number
因此,对于我的编程作业,用户必须输入年级数,但我们必须检查输入和 return 正确的错误。该数字必须是正数,并且程序需要区分错误并给出正确的响应并循环返回直到输入正确的数字。我得到了错误检查部分,但我无法让程序继续下一部分。任何帮助将不胜感激
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
if (numGrade < 0){
System.out.println("Your number of grades needs to positive! Try again");
count1++;
continue;
}
}
else{
System.out.println("You did not enter a number! Try again");
count1++;
input.next();
continue;
}
}while (count1 > 0);
试试这个,
//use a boolean to tell the loop to continue or not
boolean cont = true;
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
//I assume 0 is a valid response (not a negative int)
if (numGrade <= 0){
System.out.println("Your number of grades needs to positive! Try again");
continue;
}
else {
cont = false;
System.out.println("Your input is valid! Value entered is " + numGrade);
}
}
else {
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
}
while (cont);
因此,对于我的编程作业,用户必须输入年级数,但我们必须检查输入和 return 正确的错误。该数字必须是正数,并且程序需要区分错误并给出正确的响应并循环返回直到输入正确的数字。我得到了错误检查部分,但我无法让程序继续下一部分。任何帮助将不胜感激
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
if (numGrade < 0){
System.out.println("Your number of grades needs to positive! Try again");
count1++;
continue;
}
}
else{
System.out.println("You did not enter a number! Try again");
count1++;
input.next();
continue;
}
}while (count1 > 0);
试试这个,
//use a boolean to tell the loop to continue or not
boolean cont = true;
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
//I assume 0 is a valid response (not a negative int)
if (numGrade <= 0){
System.out.println("Your number of grades needs to positive! Try again");
continue;
}
else {
cont = false;
System.out.println("Your input is valid! Value entered is " + numGrade);
}
}
else {
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
}
while (cont);