提问人:lighdhftr3456 提问时间:8/30/2023 更新时间:8/30/2023 访问量:27
如何在Java中创建多个自定义InputMismatch Exception消息?
How to create multiple custom InputMismatch Exception messages in Java?
问:
是否可以为 1 个 try-catch 块中的每个变量 num、price 和 item 提供自定义异常消息,或者我是否需要多个 try 和 catch 块?因此,如果用户输入字母而不是“num”变量的整数,则异常消息将是“必须是 1-10 之间的整数”。如果用户输入字母而不是“price”变量的双精度,则异常消息将是“必须是 0.00-100.00 之间的双精度”。
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int num;
double price
String item;
try {
System.out.println("Input must be an integer between 1-10");
num = scan.nextInt();
System.out.println("Input must be a double between 0.00-100.00");
price = scan.nextDouble();
System.out.println("Input must be a string");
item = scan.next();
} catch(InputMismatchException e) {
System.out.println("Custom Message Here");
}
}
答:
0赞
Abra
8/30/2023
#1
块中的代码与任何其他类型的 [代码] 块中的 [Java] 代码没有什么不同。
我建议初始化变量和(为无效值)并使用块中的语句。
如果变量(即 或 ) 具有其初始值,这意味着在用户输入该变量的值期间发生错误。
由于两者的有效值范围都是非负数,因此在下面的代码中,我将它们都初始化为 -1(减去 1)。catch
num
price
if
catch
num
price
num
price
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = -1;
double price = -1.0;
String item = null;
try {
System.out.println("Input must be an integer between 1-10");
num = scan.nextInt();
System.out.println("Input must be a double between 0.00-100.00");
price = scan.nextDouble();
scan.nextLine();
System.out.println("Input must be a string");
item = scan.nextLine();
}
catch(InputMismatchException e) {
if (num < 0) {
System.out.println("Invalid 'num'.");
}
else if (price < 0.0D) {
System.out.println("Invalid 'price'.");
}
else {
e.printStackTrace();
}
}
}
0赞
DevilsHnd - 退した
8/30/2023
#2
在我看来,你不应该故意想要任何尝试/捕捉机制来做这种事情。如果可以,请使用不需要错误捕获的代码,例如(阅读代码中的注释):
// OS related newline character sequence:
final String LS = System.lineSeparator();
/* Open a Keyboard input stream. Don't close this object!
If you do then you will have to restart your application
to use it again. The JVM will automatically close this
Stream (System.in) when the application closes (ends). */
final Scanner userInput = new Scanner(System.in);
int qty;
double price;
String item;
// PROMPT #1 - Ask for an integer value between 1 and 10 (inclusive):
String entryString = "";
// Keep looping for as long as entryString is empty ("") {null-String}:
while (entryString.isEmpty()) {
// The Actual Prompt displayed to User:
System.out.println("Enter a Quantity value between 1 and 10 (inclusive):");
System.out.print("Your Entry (or q to quit): -> ");
/* Get User's numerical input. Trim off any leading/trailing
whitespaces from the entry if they were accidently placed
there. */
entryString = userInput.nextLine().trim();
// Did User want to quit?
if (entryString.equalsIgnoreCase("q")) {
// Yes!...Then Quit!
System.out.println("Quitting - Bye Bye");
return;
}
// Validate User's entry for this prompt:
// Was a proper entry made (1 to 10)?
if (!entryString.matches("[1-9]|10")) {
// No...Is it because not all characters supplied are numerical digits?
if (!entryString.matches("\\d+")) {
//Yes...that's the problem...Inform User and allow to try again.
System.out.println("Invalid Numerical Entry! (" + entryString
+ ") You must supply numerical digits only! Try Again..." + LS);
}
/* No...Then it must be because the numerical value supplied
does fall within the required inclusive range of 1 to 10. */
else {
// Inform the User of the issue and allow to try again.
System.out.println("Invalid Numerical Entry! (" + entryString
+ ") You must supply a numerical value from 1 to 10 only! "
+ "Try Again..." + LS);
}
// For either reason...Empty varaible to ensure re-loop;
entryString = "";
}
}
// If we make it to this point in code then...the entry passed validation:
qty = Integer.parseInt(entryString);
// ==============================================================================
System.out.println();
// PROMPT #2 - Ask for a Floating Point Value from 0.0 to 100.0 (inclusive):
entryString = ""; // Empty the entryString variable for re-use:
// Keep looping for as long as entryString is empty ("") {null-String}:
while (entryString.isEmpty()) {
// The Actual Prompt displayed to User:
System.out.println("Enter a Price Per Item value between 0.00 and 100.00 (inclusive):");
System.out.print("Your Entry (or q to quit): -> ");
/* Get User's numerical input. Trim off any leading/trailing
whitespaces from the entry if they were accidently placed
there. */
entryString = userInput.nextLine().trim();
// Did User want to quit?
if (entryString.equalsIgnoreCase("q")) {
// Yes!...Then Quit!
System.out.println("Quitting - Bye Bye");
return;
}
// Validate User's entry for this prompt:
/* Was a proper entry made (1 to 100 OR 1.0 to 100.0)?
To be honest, it makes no difference if an integer
value is supplie from 1 to 100 or a floating point
value. It can save the User with the hassle of adding
.0 to the end of the entry. This is done when the
supplied value is converted to a double data type
anyway.*/
if (!entryString.matches("-?\\d+(\\.\\d+)?")
|| Double.parseDouble(entryString) < 0.0d
|| Double.parseDouble(entryString) > 100.0d) {
/* No...Is it because not all characters supplied are
numerical digits (ignoring the decimal point)? */
if (!entryString.replace(".", "").matches("\\d+")) {
//Yes...that's the problem...Inform User and allow to try again.
System.out.println("Invalid Numerical Entry! (" + entryString
+ ") You must supply numerical digits only" + LS + "(with or without "
+ "the decimal point for whole values)! Try Again..." + LS);
}
/* No...Then it must be because the numerical value supplied
does fall within the required inclusive range of 1 to 10. */
else {
// Inform the User of the issue and allow to try again.
System.out.println("Invalid Numerical Entry! (" + entryString
+ ") You must supply a numerical value from 0.0 to "
+ "100.0 only! Try Again..." + LS);
}
// For either reason...Empty varaible to ensure re-loop;
entryString = "";
}
}
// If we make it to this point in code then...the entry passed validation:
price = Double.parseDouble(entryString);
// ==============================================================================
System.out.println();
// PROMPT #3 - Ask for a Description String of any content other than empty:
entryString = ""; // Empty the entryString variable for re-use:
// Keep looping for as long as entryString is empty ("") {null-String}:
while (entryString.isEmpty()) {
// The Actual Prompt displayed to User:
System.out.println("Enter an Item Description of any length:");
System.out.print("Your Entry (or q to quit): -> ");
/* Get User's String input. Trim off any leading/trailing
whitespaces from the entry if they were accidently placed
there. */
entryString = userInput.nextLine().trim();
// Did User want to quit?
if (entryString.equalsIgnoreCase("q")) {
// Yes!...Then Quit!
System.out.println("Quitting - Bye Bye");
return;
}
// Validate User's entry for this prompt:
// Was a proper entry made (a String of any length other than 0)?
if (entryString.isEmpty()) {
System.out.println("Invalid Item Description Supplied! Your entry must "
+ "contain something! Try Again..." + LS);
entryString = ""; // Empty varaible to ensure re-loop;
}
}
// If we make it to this point in code then...the entry passed validation:
item = entryString;
// ============================ DONE WITH PROMPTS ===============================
// Display input Results:
System.out.println();
System.out.println("Quantity: " + qty + " - Price Each: $"
+ String.format("%.2f", price) + " - Description: "
+ item + LS + "TOTAL Price: -> $" + String.format("%.2f", (qty * price)));
现在,这看起来像很多代码,但实际上并非如此。其中大部分是评论,如果您愿意,可以删除。
您还会注意到,只有 Scanner#nextLine() 方法用于获取用户输入。我喜欢这种方法相对于其他方法的灵活性。
有三个提示,每个提示都使用 String#matches() 方法和小正则表达式 (regex) 进行验证。
使用的表达式:
"[1-9]|10"
包含从 1 到 10 的任何值(包括 1 到 10 的字符串);"\\d+"
包含从 0 到 9 的所有数字的字符串;"-?\\d+(\\.\\d+)?"
一个 String 包含 数值有符号或无符号整数或浮点值。
下一个:在输出打印行中包括输入
评论
RuntimeException