如何处理 java 异常 InputMismatchException 以及自定义异常?
How to handle java exception InputMismatchException along with custom exceptions?
我正在制作一个简单的程序,它是一个猜谜游戏,您需要做的就是猜测随机数。只要您没有得到正确答案,它就会一直要求输入。
我创建了两个异常,当输入值高或低时抛出这两个异常。
我还需要使用另一个异常,即 InputMismatchException,但是当它使用它时,它给了我一个无限循环。它不会询问用户输入,而是直接跳到 InputMismatchException。我如何让它与我的自定义异常一起工作?
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int min = 1, max = 50;
final int random = (int) Math.floor(Math.random() * (max - min + 1) + min);
boolean status = false;
int count = 0;
while (status != true) {
try {
System.out.println("Guess a number from 1 to 50: ");
int answer = scan.nextInt();
if (answer < random) {
throw new InputTooLowException("");
} else if (answer > random) {
throw new InputTooHighException("");
} else if (answer == random) {
System.out.println("\n" + "Congratulations! You got it in " + count + " attempt/s");
status = true;
}
} catch (InputTooLowException e) {
System.out.println("Too low. Try again.");
status = false;
count = count + 1;
} catch (InputTooHighException e) {
System.out.println("Too high. Try again.");
status = false;
count = count + 1;
} catch (InputMismatchException e) {
System.out.println("Invalid Input");
status = false;
}
}
}
}
这个程序适合我。
同样,我想强调这是 bad/non-idiomatic 异常的使用。
我强烈推荐 Joshua Bloch 的名著“Effective Java”。第 10 章第 69 项是关于此的:“仅在异常情况下使用异常”。
卡内基梅隆大学软件工程研究所的coding guidelines也有这个。
现在关于 无限循环 :我没有意识到 InvalidInputException
不是 您的自定义 异常之一,但是来自 java.util 并被 scan.nextInt
.
抛出
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
这意味着,如果您输入文本而不是数字,Scanner 会让您知道,但不会 简单地丢弃输入。你必须自己处理。例如,通过调用 next
。我在这里添加了一个检查 hasNext
。用户可以按 Ctrl+d,这意味着类似于“文件结尾”(EOF)。这将关闭输入流。我的检查在这里防止了错误,但是你对 nextInt
的调用可能会抛出 NoSuchElementException
。这应该在实际代码中处理,但我怀疑你的教授会注意到。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int min = 1, max = 50;
final int random = (int) Math.floor(Math.random() * (max - min + 1) + min);
boolean status = false;
int count = 0;
while (status != true) {
try {
System.out.println("Guess a number from 1 to 50: ");
int answer = scan.nextInt();
// Note that this is a _terrible_ use of Exceptions
// and _bad practice_.
if (answer < random) {
throw new InputTooLowException("");
} else if (answer > random) {
throw new InputTooHighException("");
} else if (answer == random) {
System.out.println("\n" + "Congratulations! You got it in " + count + " attempt/s");
status = true;
}
} catch (InputTooLowException e) {
System.out.println("Too low. Try again.");
count = count + 1;
} catch (InputTooHighException e) {
System.out.println("Too high. Try again.");
count = count + 1;
} catch (InputMismatchException e) {
System.out.println("Invalid Input");
// Check if there actually is an invalid token
if (scan.hasNext()) {
// Discard invalid token
scan.next();
}
}
}
}
// Defining Exceptions here, but could do it in their own files.
private static class InputTooHighException extends Exception {
public InputTooHighException(String msg) { super(msg); }
}
private static class InputTooLowException extends Exception {
public InputTooLowException(String msg) { super(msg); }
}
}
我正在制作一个简单的程序,它是一个猜谜游戏,您需要做的就是猜测随机数。只要您没有得到正确答案,它就会一直要求输入。
我创建了两个异常,当输入值高或低时抛出这两个异常。
我还需要使用另一个异常,即 InputMismatchException,但是当它使用它时,它给了我一个无限循环。它不会询问用户输入,而是直接跳到 InputMismatchException。我如何让它与我的自定义异常一起工作?
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int min = 1, max = 50;
final int random = (int) Math.floor(Math.random() * (max - min + 1) + min);
boolean status = false;
int count = 0;
while (status != true) {
try {
System.out.println("Guess a number from 1 to 50: ");
int answer = scan.nextInt();
if (answer < random) {
throw new InputTooLowException("");
} else if (answer > random) {
throw new InputTooHighException("");
} else if (answer == random) {
System.out.println("\n" + "Congratulations! You got it in " + count + " attempt/s");
status = true;
}
} catch (InputTooLowException e) {
System.out.println("Too low. Try again.");
status = false;
count = count + 1;
} catch (InputTooHighException e) {
System.out.println("Too high. Try again.");
status = false;
count = count + 1;
} catch (InputMismatchException e) {
System.out.println("Invalid Input");
status = false;
}
}
}
}
这个程序适合我。 同样,我想强调这是 bad/non-idiomatic 异常的使用。
我强烈推荐 Joshua Bloch 的名著“Effective Java”。第 10 章第 69 项是关于此的:“仅在异常情况下使用异常”。
卡内基梅隆大学软件工程研究所的coding guidelines也有这个。
现在关于 无限循环 :我没有意识到 InvalidInputException
不是 您的自定义 异常之一,但是来自 java.util 并被 scan.nextInt
.
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
这意味着,如果您输入文本而不是数字,Scanner 会让您知道,但不会 简单地丢弃输入。你必须自己处理。例如,通过调用 next
。我在这里添加了一个检查 hasNext
。用户可以按 Ctrl+d,这意味着类似于“文件结尾”(EOF)。这将关闭输入流。我的检查在这里防止了错误,但是你对 nextInt
的调用可能会抛出 NoSuchElementException
。这应该在实际代码中处理,但我怀疑你的教授会注意到。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int min = 1, max = 50;
final int random = (int) Math.floor(Math.random() * (max - min + 1) + min);
boolean status = false;
int count = 0;
while (status != true) {
try {
System.out.println("Guess a number from 1 to 50: ");
int answer = scan.nextInt();
// Note that this is a _terrible_ use of Exceptions
// and _bad practice_.
if (answer < random) {
throw new InputTooLowException("");
} else if (answer > random) {
throw new InputTooHighException("");
} else if (answer == random) {
System.out.println("\n" + "Congratulations! You got it in " + count + " attempt/s");
status = true;
}
} catch (InputTooLowException e) {
System.out.println("Too low. Try again.");
count = count + 1;
} catch (InputTooHighException e) {
System.out.println("Too high. Try again.");
count = count + 1;
} catch (InputMismatchException e) {
System.out.println("Invalid Input");
// Check if there actually is an invalid token
if (scan.hasNext()) {
// Discard invalid token
scan.next();
}
}
}
}
// Defining Exceptions here, but could do it in their own files.
private static class InputTooHighException extends Exception {
public InputTooHighException(String msg) { super(msg); }
}
private static class InputTooLowException extends Exception {
public InputTooLowException(String msg) { super(msg); }
}
}