在检查元音时,为什么我的for循环在第一个元素之后退出? Java的

时间:2017-02-14 17:33:42

标签: java for-loop

我是for循环和增强for循环的新手,所以也许有人可以帮助澄清为什么我的增强for循环检查元音只是在退出循环之前检查第一个元素?

我在for循环下面放了一个println(元音)来测试它的输出,然后再检查输入,它只是拉动A'。辅音都工作得很好,所以此时我有点困惑。

任何可以指出我正确的方向来确定或解决或帮助我理解的事情都将非常感激。

谢谢!

import java.util.Scanner;

公共类WordStart {

public static void main(String[] args) {

    Scanner in=new Scanner(System.in);

    char[] consonants = {'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z'};
    char[] vowels = {'A','E','I','O','U'};
    System.out.println("Please enter a word: ");
    String word=in.nextLine();
    char firstLetter=(Character.toUpperCase(word.charAt(0)));
    int found = -1;




    for (char vowel: vowels)
{//System.out.println(vowel);
        if (firstLetter == vowel)
    {
        found = 1;
            if (found==1)
            {
                System.out.print(firstLetter+" is a vowel.\n");
                System.exit(0);
            }

    }
     for (char consonant: consonants)   
        {
            if (firstLetter == consonant)
            {
            found = 2;
                {
                    if (found==2)
                    {
                        System.out.print(firstLetter+" is a consonant.\n");
                        System.exit(0);

                    }

                }
            }    
        }
     if (found<=0)
     {
         System.out.println(firstLetter+" is not a vowel or consonant.\n");
         System.exit(0);
     }

}

这是正确的代码:

import java.util.Scanner; 公共类WordStart {

public static void main(String[] args) {
    Scanner in=new Scanner(System.in);

    char[] consonants = {'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z'};
    char[] vowels = {'A','E','I','O','U'};
    System.out.println("Please enter a word: ");
    String word=in.nextLine();
    char firstLetter=(Character.toUpperCase(word.charAt(0)));
    int found=0;

    for (char vowel:vowels)
    {
        if(firstLetter==vowel)
        {
            found=1;
            System.out.println(firstLetter+" is a vowel.");
            System.exit(0);

        }
    }

     for (char consonant: consonants)   
        {
            if (firstLetter == consonant)
            {
            found = 2;
            System.out.print(firstLetter+" is a consonant.\n");
            System.exit(0);
            }    
        }
     if (found<=0)
     {
         System.out.println(firstLetter+" is not a vowel or consonant.\n");
         System.exit(0);
     }       
}

}

格式化完全不正确。清理完代码后,我发现问题出在我自己的疏忽上。

谢谢大家!

1 个答案:

答案 0 :(得分:4)

如果您希望程序继续执行,则需要删除System.exit(0);语句。

尝试替换

System.exit(0);

break;

它将停止执行当前for循环并从下一循环开始。