2016-02-29 51 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来提高效率。