2016-01-27 192 views
0

我正在製作一個程序,它將一個句子作爲輸入,創建這些單詞的數組並顯示一個單詞是多餘的還是不是。循環的邏輯問題

如果掃描了「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."); 
    } 

} 
+1

你的問題是什麼? – Satya

+2

「while(b)」always while「while(false)」,你永遠不會進入這個循環,b永遠不會成真。 – Berger

+0

我剛剛eddited if(s.compareTo(T [i]!= 0)into f(s.compareTo(T [i] == 0) – Aleks

回答

0

這裏是工作的代碼 -

 while(o<T.length && !b) 
     { 
      if(o!=i) 
      { 

       if(s.equals(T[o])) 
       { 
        b=true; 
       } 
      } 
      o++; 
     } 
     i+=1; 
    } 
+0

does not work。 !b == true,while循環應該停止一次b是真的 – Aleks

+0

如果你在進入循環之前有布爾型b = false;根據原始問題,我的解決方案將工作。 –

0

我只定了!

我實際上與布爾值x)x我沒有意識到雖然(假)不能循環,但while(b ==假)可以。

boolean b=true; 
    for(String s : T) 
    { 
     System.out.println("T["+i+"] = "+ s); 
     int o = 0; 
     while(b && o<T.length) 
     { 
      if(o!=i) 
      { 

       if(s.compareTo(T[o])==0) 
       { 
        b=false; 
       } 
      } 
      o+=1; 
     } 
     i+=1; 
    } 

謝謝你們!