2013-08-28 49 views
2
public static void main (String Args[]) throws IOException{ 

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.println("Enter String"); 
    String s = br.readLine(); 
    s=s+" "; 
    s.toLowerCase(); 
    String word=""; 
    String max=""; 
    int count=0; 

    for(int i=0; i<s.length();i++){ 
     char ch = s.charAt(i); 
     while(ch!=' ') 
      word+=ch; 

     if(word.length()>max.length()){ 
      max=word; count++; 
     } 
     else count++; 
    }System.out.println(max+" , "+count); 
} 
} 

我想查找字符串中最大的單詞而不使用拆分或類似的東西,並且還要計算句子中有多少單詞。 當我輸入任何東西,然後按回車沒有任何反應。問題是什麼?BufferedReader即使按下輸入鍵後也沒有輸入

回答

1

有從控制檯讀取輸入沒有問題。

while(ch!=' ') 
    word+=ch; 

它使無限循環。你應該更新這個while-loop像 -

while(ch!=' '){ 
    word+=ch; 
    ch = s.charAt(++i); 
} 
+1

謝謝。這是一個蹩腳的錯誤。 – NobleSiks

+0

歡迎您:)) –

0

您在擁有無限循環有

while(ch!=' ') 
      word+=ch; 
0

男人,它的工作原理,在readLine沒有錯誤。

但我看到一個無限循環的:

while(ch!=' ') 
     word+=ch; 

請檢查邏輯,一旦...

0
public class LengthiestWord { 

    public static void main (String Args[]) throws IOException{ 

     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     System.out.println("Enter String"); 
     String s = br.readLine(); 
     s=s+" "; 
     s.toLowerCase(); 
     String word=""; 
     String max=""; 
     int count=0; 

     for(int i=0; i<s.length();i++){ 
      char ch = s.charAt(i); 
      while(ch!=' '){ 
       word+=ch; 
       ch = s.charAt(++i); 
      } 

      if(word.length()>max.length()){ 
       max=word; 
       word=""; 
       count++; 
      } 
      else { 
       count++; 
       word=""; 
      } 
     } 
     System.out.println(max+" , "+count); 
    } 
} 

O/P ---- >>>>

進入字符串

所有錯誤都是固定的

錯誤,4