如何结束持续接受字符的while循环

时间:2019-01-11 01:14:19

标签: java

我正在检查输入的是元音,辅音还是其他。当输入任何其他数据类型(int,double,long等)时,我想突破while循环。预先感谢您的协助。

import java.util.Scanner;
/**
 *
 * @author Babatunde
 */
public class vowelConsonantOne {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        char ch;
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("Enter an Alphabet");
            ch = sc.next().charAt(0);

            if (ch == 'A' || ch == 'a' || ch == 'E' || ch == 'e' || ch == 'I' || ch == 'i' || ch == 'O' || ch == 'o' || ch == 'U' || ch == 'u') {
                System.out.println("This is a vowel");
            } else {
                System.out.println("This is a consonant");
            }
        }
    }

}

2 个答案:

答案 0 :(得分:1)

使用Character类及其各种方法:Character.isLetter应该可以完成工作(isAlphabetic(int)仅适用于代码点)。

        if (ch == 'A' || ch == 'a' || ch == 'E' || ch == 'e' || ch == 'I' || ch == 'i' || ch == 'O' || ch == 'o' || ch == 'U' || ch == 'u') {
            System.out.println("This is a vowel");
        } else if (Character.isLetter(ch)) {
             System.out.println("This is a consonant");
        } else {
          break; // exit the loop.
        }

或者,如果您不想退出循环并继续阅读字符:

     for(;;) {
        System.out.println("Enter an Alphabet");
        char ch = sc.next().charAt(0);
        if (ch == 'A' || ch == 'a' || ch == 'E' || ch == 'e' || ch == 'I' || ch == 'i' || ch == 'O' || ch == 'o' || ch == 'U' || ch == 'u') {
            System.out.println("This is a vowel");
        } else if (Character.isLetter(ch)) {
             System.out.println("This is a consonant");
        }
      }

顺便说一句,您不需要Scanner类:

InputStreamReader isr = new InputStreamReader(System.in, StandardDefaultCharsets.UTF_8);
for (;;) {
  System.out.println("Enter an Alphabet");
  int n = isr.read();
  if (n == -1) break; // end of stdin.
  char ch = (char) n;
  // the if here
}

答案 1 :(得分:0)

如果添加Character.toLowerCase(),则只需要检查小写字符。 要退出while循环,请使用

break;

(真实的)部分:

while (true) {
    System.out.println("Enter an Alphabet");
    ch = Character.toLowerCase(sc.next().charAt(0));

    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
        System.out.println("This is a vowel");
    } else {
        System.out.println("This is a consonant");
        sc.close();
        break;
    }
}