2015-10-07 31 views
1

我正在製作一個程序,該程序從用戶處取得一個字符串,並用分隔符逐字分開,並且它幾乎完成。但是,在第一個完整循環之後,來自用戶的下一個輸入不會通過最後的while循環。如何在循環中保留字符串輸入

下面是我在談論的代碼段:

do 
    { 
    System.out.println ("\nEntered String: " + s1 + "\n"); 

    while (input.hasNext()) 
    { 
     word++; 

     System.out.println ("Word #" + word + ": \t" + input.next()); 
    } 
     System.out.print ("\nEnter 'q' to quit, enter string to continue: \t"); 
     s1 = scan.nextLine(); 

    } while (!s1.equals("q")); 

我想,我需要周圍的字增量和打印線另一while循環,並有input.hasNext內繼續序列( )循環,因爲這是我得到一個類似的程序使用int來工作,但我不知道這將如何處理字符串。

有什麼建議?

編輯:澄清,現在我的代碼的輸出是這樣的:

輸入一句:這是一個句子

輸入的字符串:這是一個句子

詞#1 :本

字#2:是

字#3:一個

詞#4:句子

輸入 'Q' 退出,輸入字符串繼續:另一句話

輸入的字符串:另一句話

輸入 'Q' 退出,輸入字符串繼續:

我需要「的另一句話」打印出像「這是一句」

+0

[java:while循環語句在進入大括號之前的分號之前帶有分號?](http:// stackoverflow。com/questions/12658242/java-while-loop-statement-with-a-semicolon-before-going-into-statements-betwe) –

+0

'input'的值是什麼? – nubteens

+0

輸入用於分隔符,用於輸入用戶輸入的字符串s1。它的工作方式與此處幾乎相同:http://javatutorialhq.com/java/util/scanner-class-tutorial/hasnext-string-pattern-method-example/但我已更改我的代碼,以便它允許用戶輸入從掃描儀。 – Len

回答

0

我不明白到底出了什麼問題,因爲您的代碼不編譯。但是不需要另一個循環。以下是一些可用的代碼:

Scanner scan = new Scanner(System.in); 
System.out.print("\nEnter a sentence:"); 
String s1 = scan.nextLine(); 

do 
{ 
    System.out.println("\nEntered String: " + s1 + "\n"); 

    Scanner input = new Scanner(s1); 
    int word = 0; 
    while (input.hasNext()) 
    { 
     word++; 
     System.out.println("Word #" + word + ": \t" + input.next()); 
    } 

    System.out.print("\nEnter 'q' to quit, enter string to continue: \t"); 
    s1 = scan.nextLine(); 

} while(!s1.equals("q")); 

scan.close(); 
+0

修好了!我只需要將掃描儀輸入放在do-while循環中。謝謝! – Len

0

你可以試試這個,如果它的工作原理。它與你需要的結果相同。

Scanner scan = new Scanner(System.in); 
    String s1 = scan.nextLine(); 
    do { 
     String input[] = s1.split(" "); 
     System.out.println ("\nEntered String: " + s1 + "\n"); 
     for(int i = 0; i < input.length; i++) { 
      System.out.println ("Word #" + i+1 + ": \t" + input[i]); 
     } 
     System.out.print ("\nEnter 'q' to quit, enter string to continue: \t"); 
     s1 = scan.nextLine(); 
    } while (!s1.equals("q")); 
0

您正在使用

while (input.hasNext()) 

我想輸入一個掃描對象,所以你應該做這樣的事情在使用之前(但在進入循環前):

Scanner input = new Scanner(System.in); 
0

我不推薦使用scanner.next()while循環,我會推薦使用以下API:

String.split 
Scanner.nextLine 

事情是這樣的:

while(input.hasNextLine()) { 
    String line = input.nextLine(); 
    String[] words = line.split("delimeter"); 
    if(words.length < 1 || words[words.length - 1].equals("q")) { 
     break; 
    } 
} 
相關問題