2016-10-04 128 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