2016-01-27 198 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; 
    } 

谢谢你们!