Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何结束持续接受字符的while循环_Java - Fatal编程技术网

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

Java 如何结束持续接受字符的while循环,java,Java,我正在检查输入是否是元音、辅音或其他。我想在输入任何其他数据类型(int、double、long等)时中断while循环。提前感谢您的帮助 import java.util.Scanner; /** * * @author Babatunde */ public class vowelConsonantOne { /** * @param args the command line arguments */ public static void ma

我正在检查输入是否是元音、辅音或其他。我想在输入任何其他数据类型(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");
            }
        }
    }

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

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

     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");
        }
      }
顺便说一下,您不需要
扫描仪
类:

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
}

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

break;
虽然(正确)部分:


目前正在发生什么?如果在我遇到另一种数据类型并中断while循环后,我如何让程序在不必重新运行程序的情况下再次继续检查字母表?“继续检查字母表”需要保持在while循环中,正如当前编码的那样。如果你想这样做,为什么要首先打破循环?FWIW,你的意思是“字母字符”(或者可能是“字母”),而不是“字母表”。例如,字母表是ABCDEFGHIJKLMNOPQRSTUVWXYZ。修正了我的答案。
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;
    }
}