使用异常处理强制用户在Java中输入char(字母)而不是String

时间:2017-04-17 09:13:05

标签: java exception-handling char

说我有一些代码:

Scanner scan = new Scanner(System.in);

System.out.print("Please input a letter: ");
char userLetter = nextLine().charAt(0);

我想使用异常处理来确保用户只输入一个字母而已。有没有办法做到这一点?

5 个答案:

答案 0 :(得分:1)

如果你需要介绍异常处理,我会这样做:

Scanner scan = new Scanner(System.in);
char c;
while(true) {
    System.out.print("Please input a letter: ");
    try {
        String s = scan.next();
        if(s.length() > 1) {
            throw new RuntimeException("Input too long!");
        }
        c = s.charAt(0);
        if (Character.isLetter(c)){
            throw new RuntimeException("Char is not a letter!");
        }

        // here you can break the loop and do whatever

    } catch(RuntimeException re){
        System.out.print(re.getMessage());
        // you can break the loop or try again
    }
}

P.S。在实际应用程序中,使用异常来控制执行流程被认为是一种不好的做法。所以请记住,此代码只能用作练习。

答案 1 :(得分:0)

您可以检查String的长度,如果它大于1,则<:p>

String s = null;
do{
    System.out.println("Enter Character : ");
    s = scan.next();
    if(s.length()!=1)
       System.out.println("Error");
}while(s.length()!=1);
System.out.println(s.charAt(0));

如果需要,您可以为Character#isLetter添加另一项检查。

答案 2 :(得分:0)

坦率地说,在这种情况下,我不会使用例外。什么都没有&#34;特殊&#34;继续 - 只是提供错误输入的用户。您可以检查并提示输入不同的内容:

Scanner scan = new Scanner(System.in);

System.out.print("Please input a letter: ");
String line = nextLine();
while (line.length() != 1 || !Character.isLetter(line.charAt(0))) {
    System.out.print("That's not a letter. Please try again: ");
    String line = nextLine();
}

答案 3 :(得分:0)

如果需要抛出异常,你可以这样做:

Scanner scanner = new Scanner(System.in);
String input = scanner.next();

if(input.length() != 1){
    throw new Exception("...");
}

char userLetter = input.charAt(0);

我认为这应该有用。

答案 4 :(得分:0)

异常不应该用于可能经常发生的情况......相反,我们应该使用if ... else来处理经常出现的情况......

为什么不使用这样的东西: -

Scanner input = new Scanner(System.in);
String text = new String();

do {

    System.out.print("Type a character: ");
    text = input.nextLine();

    if(text.length() > 1) {
         System.out.println("Kindly enter only one character...");
    }

} while(text.length() > 1);