Do While Loop Problems



所以我提示用户输入1-12之间的数字。如果它们不满足要求,循环将再次运行它。我的循环总是出错。

代码

import java.util.Scanner;
public class HW7 {
public static int inputMonth(Scanner in) {
int input = Integer.MIN_VALUE;
boolean flag = true;
do {
System.out.println("Enter a month between 1-12:");
if (in.hasNextInt()) {
input = in.nextInt();
in.nextLine();
if (input >= 1 && input <= 12) {
flag = false;
}
}
} while (flag);
return input;
}
}

错误

输入1-12之间的月份:
输入1-12间的月份:
输入1至12间的月份


。。。

它还在继续。

您不需要条件if(in.hasNextInt())。此外,应为每个错误/无效输入重置flag,例如flag = false应置于循环内。我还建议您放入异常处理代码来处理无效输入。

import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
// Test
Scanner in = new Scanner(System.in);
System.out.println(inputMonth(in));
}
public static int inputMonth(Scanner in) {
int input = Integer.MIN_VALUE;
boolean flag = false;
do {
flag = false;
System.out.print("Enter a month between 1-12: ");
try {
input = in.nextInt();
if (input < 1 || input > 12) {
System.out.println("The month must be between 1-12. Please try again.");
in.next();
flag = true;
}
} catch (InputMismatchException e) {
System.out.println("This is an invalid input. Please try again.");
in.next();
flag = true;
}
} while (flag);
return input;
}
}

样本运行:

Enter a month between 1-12: 2
2

另一个样本运行:

Enter a month between 1-12: w
This is an invalid input. Please try again.
Enter a month between 1-12: 15
The month must be between 1-12. Please try again.
0
Enter a month between 1-12: 3
3

执行类似的操作

import java.util.Scanner;
public class test { 
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
inputMonth(in);
}
public static int inputMonth(Scanner in) {
int input= Integer.MIN_VALUE; 
boolean flag=true;
do{
System.out.println("Enter a month between 1-12:");
if(in.hasNextInt()){
input=in.nextInt();
in.nextLine();
if(input>=1 && input<=12) {
flag=false;

}
}   
} while(flag);
return input;
}
}

为了使用Scanner对象,你必须初始化它,你还需要从java导入库,这就是为什么import java.util.Scanner;

在主方法中使用此代码:

Scanner input = new Scanner(System.in);
inputMonth(input);

最新更新