2016-02-29 74 views
0

我試圖讀取用戶輸入,然後將這些單詞與它們之間的空格連接起來。我無法弄清楚循環中的邏輯。我還希望用戶能夠在完成輸入單詞時告訴我的程序。這是我到目前爲止......這並不多。使用do while循環連接

Scanner in = new Scanner(System.in); 

    String userWords = ""; 
    int number = 0; 

    System.out.println("Enter words to build a sentence"); 
    userWords = in.nextLine(); 

    int i = 1; 
    do { 
     System.out.println(userWords); 
     i++; 
    } while (!(userWords.equals(null))); { 
     System.out.println(userWords + " "); 
    } 

回答

0

嘗試用:

Scanner in = new Scanner(System.in); 
    String userWords = ""; 
    String currentWord = ""; 
    // now we print a prompt for user 
    System.out.println("Enter words to build a sentence"); 
    // here is the reading loop 
    do { 
     // now we read next line from user 
     currentWord = in.nextLine(); 
     // now we add the user input to the userWords with " " 
     userWords += currentWord +" "; 
     // we end the loop when the currentWord will be empty 
    } while (!(currentWord.trim().isEmpty())); 
    // now we print all the words 
    System.out.println(userWords); 
+0

當我輸入循環的while部分時,它會給出錯誤,並說「左側必須解析爲變量」 – Harry

+0

現在就試試吧,我已經修復了這個 –

+0

,這很好用謝謝 – Harry

2
Scanner in = new Scanner(System.in); 

    String enteredWord = ""; 
    StringBuilder builder = new sb(); 
    System.out.println("Enter words to build a sentence"); 
    enteredWord = in.nextLine(); 
    do { 

     sb.append(enteredWord); 
     sb.append(" "); 
     enteredWord = in.nextLine(); 

    } while (!(enteredWord.equals("exit"))); 
//you may want to use a special case like %% instead because exit can be in a sentence{ 
      System.out.println(sb.toString()); 

應該對我沒有任何地方馬上來測試它的大部分工作。每循環一次,循環就會在單詞後面添加一個空格,並要求輸入一個新單詞。你可以使用userwords += in.nextline() + " ";,但是在一個循環中,我也會使用stringbuilder來提高效率。