2016-02-29 221 views
0

我正在嘗試編寫一個程序,該程序需要用戶輸入的單詞並使用這些單詞構建一個句子。所以如果你輸入「Hello」和「World」,它將返回「Hello World」。但是,如果我輸入「我」,「愛」和「狗」,它會返回「愛狗完成」。 (做是我的定點用戶退出我不知道如何做到這一點將用戶輸入的單詞組合成一個語句

import java.util.Scanner; 

public class SentenceBuilder { 


public static void main(String[] args) { 

    Scanner scnr = new Scanner(System.in); 

    String word = " "; 
    String sentence = " "; 
    final String SENTINEL = "done"; 
    double count = 0; 

    System.out.println("Enter multiple words: "); 
    System.out.println("Enter done to finish: "); 
     word = scnr.nextLine(); 


    do { 
     word = scnr.nextLine(); 
     count++; 
     sentence += word + " "; 
    } while (!(word.equalsIgnoreCase(SENTINEL))); 



    System.out.println(sentence); 
} 

} 
+2

APRT,你應該考慮'StringBuilder'或'StringBuffer'作爲字符串是不可改變的 – Pragnani

+0

@Luke哈丁嘗試下面我的解決方案.. – user3437460

回答

1

改變你的代碼如下:。

public static void main(String[] args) 
{ 
    Scanner scnr = new Scanner(System.in); 

    String word = ""; 
    String sentence = ""; 
    final String SENTINEL = "done"; 
    double count = 0; 

    System.out.println("Enter multiple words: "); 
    System.out.println("Enter done to finish: "); 
    //remove the first prompt here.. 
    do { 
     word = scnr.next(); 
     if(word.equalsIgnoreCase(SENTINEL)) //exit loop if "done" was input 
      break;   
     count++; 
     sentence += word + " "; 
    } while (!(word.equalsIgnoreCase(SENTINEL))); 

    System.out.println(sentence);   
} 

您需要移除外部一次提示你的循環,如果沒有,它不會將第一個輸入添加到你的字符串中,我添加了一個支票,一旦收到「完成」就打出來

這可能是一個來自學校的問題,因此你使用sentence += word。爲了累加字符串,最好使用StringBuilder雖然。

+0

奏效!謝謝!儘管如此,在句子的開頭仍然有一個空格。即 - 「我愛你」。任何原因爲什麼? –

+1

@LukeHarding這是因爲你宣稱單詞爲「」(空格)和句子爲「」(空格)。只要將它們聲明爲'「」',你就不會看到額外的空格。嘗試我編輯的代碼。 – user3437460

+0

這就是它!感謝您的幫助! –

0

只需以簡單的方式重新編寫塊。從答案

word = scnr.nextLine(); 
    while (!(SENTINEL.equalsIgnoreCase(word))) { 
     sentence += word + " "; 
     word = scnr.nextLine(); 
     count++; 
    } 
相關問題