我是一名新手 java 程序员,需要调整此代码,以便它捕获两个字符串而不是变量。
这是我们应该使用的原始代码:
import java.util.Scanner;
import java.util.InputMismatchException;
public class Part4 {
public static void main(String[] args) {
int userNum = 0;
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
String dump = null;
while (!inputOK) {
System.out.print("Enter a number: ");
try {
userNum = screen.nextInt();
dump = screen.nextLine();
inputOK = true;
} catch (InputMismatchException e) {
dump = screen.nextLine();
System.out.println("\"" + dump + "\" is not a legal integer, " +
"please try again!");
} // end try-catch block
} // end input loop
screen.close();
userNum = userNum + 20;
System.out.println("Your number plus 20 is " + userNum);
}
}
这是我失败的尝试:
import java.util.Scanner;
import java.util.InputMismatchException;
public class testClass {
public static void main(String[] args) {
String letter = new String();
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
String dump = null;
while (!inputOK) {
System.out.print("Enter ('y' or 'n': )");
try {
letter = screen.nextLine();
dump = screen.nextLine();
inputOK = true;
} catch (InputMismatchException e) {
dump = screen.nextLine();
System.out.println("\"" + dump + "\" is not a legal letter, " +
"please try again!");
}
}
screen.close();
System.out.println("That is a valid letter");
}
}
如果有人可以提供帮助,我们将不胜感激。 谢谢:)
最佳答案
首先,只会抛出InputMismatchException
to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
由于除了 y
和 n
之外的任何内容仍然是 String
的,因此不会抛出此错误。相反,如果不是 y
或 n
,您可以抛出新的 InputMismatchException
:
String letter = new String();
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
while (!inputOK) {
System.out.println("Enter ('y' or 'n': )");
try {
letter = screen.nextLine();
if(!letter.equals("y") && !letter.equals("n")) {
throw new InputMismatchException();
}
inputOK = true;
} catch (InputMismatchException e) {
System.out.println("\"" + letter + "\" is not a legal letter, " +
"please try again!");
}
}
System.out.println("That is a valid letter");
关闭System.in
也不是一个好习惯。一般规则是如果您没有打开资源,则不应关闭它
关于java - 如何使用 InputMismatchException 捕获字符串? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52562903/