我一直在研究這款豬拉丁語翻譯器,除了這兩個(相同)while循環沒有像預期的那樣執行外,我剛剛完成了這項工作。當我試圖翻譯一個短語時,比如「我的名字是」,它應該是「yMay amenay isway」。問題在於,由於我不知道的原因,指示的循環無限地執行。否則,我已經測試確保此代碼正常工作。我不知道如何使它工作。有什麼想法嗎?非常感謝!爲什麼會進入無限循環? (豬拉丁文)
import java.io.*;
import java.util.*;
import java.util.Arrays;
public class PigLatin
{
public static void main (String[] args)
{
System.out.print("Please enter a phrase to translate: ");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
String[] words = str.split("\\s+");
int period = words.length;
int spaces = (period - 1);
String[] word = Arrays.copyOfRange(words,0,spaces);
for (int i = 0; i < word.length; i++)
{
String a = word[i].substring(0,1);
int b = a.length();
int c = word[i].length();
while (b <= 4) //start of thought problem
{
if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
{
a = word[i].substring(0,b);
b = b + 1;
}
} // end of thought problem
if (word[i].startsWith("a") || word[i].startsWith("e") || word[i].startsWith("i") || word[i].startsWith("o") || word[i].startsWith("u"))
{
System.out.print(word[i] + "way");
}
else if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
{
String answer = word[i].substring(b,c);
System.out.print(answer + a + "ay");
}
System.out.print(" ");
}
String end = "";
for (String endArray: Arrays.copyOfRange(words,spaces,period))
{
end = end + endArray;
}
String z = end.substring(0,1);
int x = z.length();
int y = end.length();
while (x <= 4) //start of thought problem
{
if (!(z.contains("a") || z.contains("e") || z.contains("i") || z.contains("o") || z.contains("u")))
{
z = end.substring(0,x);
x = x + 1;
}
} //end of thought problem
if (end.startsWith("a") || end.startsWith("e") || end.startsWith("i") || end.startsWith("o") || end.startsWith("u"))
{
System.out.print(end + "way");
}
else if (!(z.contains("a") || z.contains("e") || z.contains("i") || z.contains("o") || z.contains("u")))
{
String answer = end.substring(x,y);
System.out.print(answer + z + "ay");
}
System.out.print(".");
}
}
我認爲b的增量應該在if語句之外。 – Jiminion
歡迎來到Stack Overflow!要求人們發現代碼中的錯誤並不是特別有效。您應該使用調試器(或者添加打印語句)來分析問題,追蹤程序的進度,並將其與預期發生的情況進行比較。只要兩者發生分歧,那麼你就發現了你的問題。 (然後,如果有必要,你應該構造一個[最小測試用例](http://sscce.org)。) –
這4個是因爲在一個單詞開頭的連續4個輔音。 – Gihadi