如何使用InputMismatchExeption捕获字符串? (Java)

时间:2018-09-28 21:35:50

标签: java

我是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");


    }
}

如果有人可以提供帮助,将不胜感激。 谢谢:)

1 个答案:

答案 0 :(得分:1)

只会首先抛出InputMismatchException

  

表示检索到的令牌与预期类型的​​模式不匹配,或者令牌超出预期类型的​​范围。

由于yn之外的任何内容仍然是String,因此不会抛出该错误。相反,如果不是InputMismatchExceptiony,则可以抛出一个新的n

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也不是一个好习惯。一般规则是,如果您没有打开资源,则不应关闭它