2016-10-04 125 views
1

我正在尋找一種方式來基本上給用戶一些控制檯輸出,看起來與他們鍵入的內容完全相同,然後再次提示輸入更多內容。問題是我有一個方法修改每個發現的不包含空格的字符串。基本控制檯輸入和輸出

在用戶給出的每個句子結尾處,我試圖找出一種方法來獲得換行符,然後再次輸出到控制檯並提示「請輸入一個句子:」。以下是我迄今爲止...

System.out.print("Please type in a sentence: "); 

    while(in.hasNext()) { 
     strInput = in.next(); 

     System.out.print(scramble(strInput) + " "); 


     if(strInput.equals("q")) { 
      System.out.println("Exiting program... "); 
      break; 
     } 

    } 

這裏是正在顯示的控制檯輸出:

Please type in a sentence: Hello this is a test 
Hello tihs is a tset 

光標停在同一條線上,如上面的例子「TSET」。

發生的是:

Please type in a sentence: Hello this is a test 
Hello tihs is a tset 
Please type in a sentence: 

具有AS和後直接「句:」光標出現在同一行

希望幫助清理我的問題。

+0

可以在同一行作爲" ... sentence: "光標出現」你只需將你的'請輸入'輸出移動到你的循環中,然後呢? –

+2

更具體。指定用戶應該輸入什麼以及程序應該給出什麼輸出作爲迴應。 – nhouser9

+0

@ nhouser9試圖更具體。我不知道如何格式化我的控制檯輸出的問題,所以它明確標識。 – ClownInTheMoon

回答

1

試試這個,我沒有測試它,但它應該做你想做的。代碼中的註釋說明了我添加的每一行:

while (true) { 
    System.out.print("Please type in a sentence: "); 
    String input = in.nextLine(); //get the input 

    if (input.equals("quit")) { 
     System.out.println("Exiting program... "); 
     break; 
    } 

    String[] inputLineWords = input.split(" "); //split the string into an array of words 
    for (String word : inputLineWords) {  //for each word 
     System.out.print(scramble(word) + " "); //print the scramble followed by a space 
    } 
    System.out.println(); //after printing the whole line, go to a new line 
} 
+1

如果你需要分開爭奪每個單詞(而不是整個句子),那麼這是要走的路。 –

+0

這工作得很好。結束了使用ArrayList的幾個不同的原因,但整體而言,該程序現在運行良好! – ClownInTheMoon

+0

@ClownInTheMoon很高興聽到= = – nhouser9

0

以下情況如何?

while (true) { 
    System.out.print("Please type in a sentence: "); 

    while (in.hasNext()) { 
     strInput = in.next(); 

     if (strInput.equals("q")) { 
      System.out.println("Exiting program... "); 
      break; 
     } 
     System.out.println(scramble(strInput) + " "); 
    } 
    break; 
} 

的變化是:

  1. 你應該打印"Please type in a sentence: "一個循環中把它重新打印。
  2. 我想你想檢查strInput是否爲「q」,並在打印之前退出,即不需要打印「q」,或者是否存在?
  3. 使用println打印加擾strInput使下"Please type in a sentence: "出現在下一行,因爲是由System.out.print輸出(無ln
+0

這將在一行中打印句子的每個單詞。不是OP想要的。 – nhouser9