我正在製作一個程序,它將一個句子作爲輸入,創建這些單詞的數組並顯示一個單詞是多餘的還是不是。循環的邏輯問題
如果掃描了「Hello Hi Hello」,程序應該通知用戶存在冗餘。
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String sentence ;
System.out.println("Enter a sentence :");
sentence = sc.nextLine();
String[] T = sentence.split(" "); //split the sentence at each " " into an array
int i=0, o=0 ; //iterators
boolean b=false; //redundancy condition
for(String s : T) // for each String of T
{
System.out.println("T["+i+"] = "+ s);
while(b) //while there's no redundancy
{
if(o!=i) //makes sure Strings are not at the same index.
{
if(s==T[o])
{
b=true; //redundancy is true, while stops
}
}
o++;
}
i+=1;
}
if(b)
{
System.out.println("There are identical words.");
}
else
{
System.out.println("There are no identical words.");
}
}
你的問題是什麼? – Satya
「while(b)」always while「while(false)」,你永遠不會進入這個循環,b永遠不會成真。 – Berger
我剛剛eddited if(s.compareTo(T [i]!= 0)into f(s.compareTo(T [i] == 0) – Aleks