[英]Why is my for loop exiting after the first element when checking vowels? Java
我是for循環和增強的for循環的新手,所以也許有人可以幫助您弄清楚為什么我的用於檢查元音的增強的for循環僅在退出循環之前才檢查第一個元素?
我在for循環下面放置了一個println(元音)以測試其輸出,然后再對照輸入進行檢查,它只是拉“ A”。 輔音都工作正常,所以在這一點上我感到有些困惑。
任何能使我指出正確方向的方法或對此有所了解或有助於我理解的任何方法,將不勝感激。
謝謝!
導入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);
}
}
}
格式完全不正確。 清理代碼后,我發現問題出在我自己的粗心。
謝謝大家!
您需要刪除System.exit(0);
語句,如果您想讓程序繼續執行。
嘗試更換
System.exit(0);
同
break;
它將停止當前for
循環的執行,並從下一個循環開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.