我是一个新手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");
}
}
如果有人能帮上忙,我将不胜感激。谢谢:)
发布于 2018-09-29 06:24:27
首先,InputMismatchException
将只抛出
表示检索的令牌与预期类型的模式不匹配,或者该令牌超出预期类型的范围。
因为除了y
和n
之外的任何东西都仍然是String
的,所以不会抛出这个问题。
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
也不是一种好的做法。一般规则是,如果您未打开资源,则不应将其关闭
https://stackoverflow.com/questions/52562903
复制相似问题