我必须创建一个 do-while 循环来验证任何非双精度且非零的用户输入。我一直在这里环顾四周并谷歌搜索,我正在创建一个无限循环,但我通过清除输入来解决这个问题。但是,现在程序不再要求用户输入,并且循环正在中断。不太确定我打破了什么。这只是代码的一部分,我还必须对 wallWidth 执行此 do-while 循环。
public class Paint1 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
boolean decimal = false;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) { //non zero numbers
throw new Exception("Invalid Input");
}
decimal = true;
}
catch (Exception e) {
System.out.println("Invalid Input");
scnr.nextDouble(); //wipe out user input
}
} while (!decimal);
循环停止并在清除无效输入后仍然创建异常而不继续。
Enter wall height (feet):
thirty
Invalid Input
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Paint1.main(Paint1.java:31)
发生的情况是,当您尝试使用
scnr.nextDouble()
擦除用户输入时,它会抛出 InputMistMatchException,但不会处理该异常。这是因为提供的输入与预期类型不匹配。要在您的环境中克服这个问题,您可以使用 scnr.nextLine()
。因为无论你输入什么,它都可以被解释为字符串。
在尝试使用 double
读取
Scanner.hasNextDouble()
之前,您应该检查是否有可用的
double
。同样,在读取(并丢弃)任何非 Scanner
标记之前,您应该检查是否存在带有 Scanner.hasNextLine()
的输入行。就像,double
do {
try {
System.out.println("Enter wall height (feet): ");
// Is there a double available?
if (scnr.hasNextDouble()) {
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
throw new Exception("Invalid Input");
}
decimal = true;
} else if (scnr.hasNextLine()) {
// Consume the next non-double token
scnr.nextLine();
} else {
// There's no more input, end the loop
break;
}
} catch (Exception e) {
System.out.println("Invalid Input");
}
} while (!decimal);
Scanner userInput = new Scanner(System.in);
String ls = System.lineSeparator();
double feet;
String inFeet = "";
while (inFeet.isEmpty()) {
System.out.print("Enter wall height (in feet): ");
inFeet = userInput.nextLine().trim();
/* Is the User entry a string representation of a unsigned
integer or floating point value and is that value greater
than 0? */
if (!inFeet.matches("\\d+(\\.\\d+)?") || Double.parseDouble(inFeet) <= 0) {
System.out.println("Entry (" + inFeet + "): -> Error - Invalid Wall "
+ "Height Entry! Try again..." + ls);
inFeet = ""; // Empty `inFeet` to ensure re-loop:
}
}
// If code makes it to here then the entry is valid!
feet = Double.parseDouble(inFeet);
System.out.println("User Entry: -> " + feet + " feet.");
如果需要,可将
Enter wall height (in feet): 0
Entry (0): -> Error - Invalid Wall Height Entry! Try again...
Enter wall height (in feet): 14.25
User Entry: -> 14.25 feet.
循环转换为
while
。