用户将需要输入一个数字来读取电表,如果用户输入的不是数字,则尝试捕获块将初始化,如果用户输入的是负数,则会弹出错误消息,请执行以下操作:虽然很简单,但是我对如何实现for循环感到困惑
public static int readStartReading(){
int reading = 0;
Scanner keyboard = new Scanner(System.in);
boolean problemFlag = false;
do {
problemFlag = false;
try {
System.out.print("Enter the meter reading at the beginning of the year: ");
String input = keyboard.nextLine();
reading = Integer.parseInt(input);// 7. Assign a value to reading through the input device
} catch (NumberFormatException x){
problemFlag = true;
System.out.println("You have to enter a number.");
} if (reading < 0){
System.out.println("The beginning meter reading cannot be negative."); }
} while (reading < 0 || problemFlag);
return reading;
}
我注意到我的错误。谢谢您的答复
答案 0 :(得分:2)
那
public static int readStartReading()
{
int reading = -1;
Scanner keyboard; //remove first reading here
while(1)
{
try
{
System.out.print("Enter the meter reading at the beginning of the year: ");
String input = keyboard.nextLine();
reading = Integer.parseInt(input);// 7. Assign a value to reading through the input device
//if control reaches here, you have a valid integer, test it
if (reading >= 0)
break;
else
System.out.println("The beginning meter reading cannot be negative.");
}
catch (NumberFormatException x)
System.out.println("You have to enter a number.");
}
return reading;
}
答案 1 :(得分:1)
您可以非常简单地将其转换为for循环,但不会有任何区别。 在您的情况下,do-while更适合。
public static int readStartReading(){
int reading = 0;
Scanner keyboard = new Scanner(System.in);
boolean problemFlag = false;
for(;reading < 0 || problemFlag;)
{
problemFlag = false;
try {
System.out.print("Enter the meter reading at the beginning of the year: ");
String input = keyboard.nextLine();
reading = Integer.parseInt(input);// 7. Assign a value to reading through the input device
} catch (NumberFormatException x){
problemFlag = true;
System.out.println("You have to enter a number.");
} if (reading < 0){
System.out.println("The beginning meter reading cannot be negative."); }
}
return reading;
}
还有几个小问题
您不需要问题标记
您正在执行两次初始读取,(用户必须输入两次值)
我会这样重写它:
public static int readStartReading()
{
int reading = 0;
Scanner keyboard; //remove first reading here
do
{
try {
System.out.print("Enter the meter reading at the beginning of the year: ");
String input = keyboard.nextLine();
reading = Integer.parseInt(input);// 7. Assign a value to reading through the input device
//if control reaches here, you have a valid integer, test it
if (reading < 0)
System.out.println("The beginning meter reading cannot be negative.");
} catch (NumberFormatException x){
reading = -1; //set reading to a negative invalid value
System.out.println("You have to enter a number.");
}
} while(reading < 0)
return reading;
}