2017-02-14 48 views
0

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

我在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); 
    } 

} 

这是正确的代码:

进口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); 
    }  
} 

}

格式化只是不正确。清理完代码后,我发现问题出在我自己的粗心大意上。

谢谢大家!

+0

因为你发现元音,所以找到设置为1,然后你检查,如果发现== 1,因此你总是退出...取出System.exit(0) –

+4

我不完全明白你的问题是的,但你打电话'System.exit(0);',它会退出程序。另外,“发现”的意义何在?你正在设置它,然后立即检查它是否是你设置的。 – Carcigenicate

+0

@Carcigenicate我明白你在说什么。上面的代码是如何代替的? – Chez

回答

4

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

尝试

break;

更换

System.exit(0);

它将停止当前for循环的执行,并与下一个循环开始。

相关问题