我正在寻找一种方法,基本上向用户返回一些看起来与他们输入内容相同的控制台输出,然后再次提示输入更多内容。问题是我有一个方法可以修改发现的每个不包含空格的字符串。
在用户给出的每个句子的末尾,我试图找出一种方法来获取换行符,然后提示再次输出到控制台说“请键入一个句子:”。这是我到目前为止所拥有的......
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:
光标与“sentence:”
之后出现在同一行希望这有助于澄清我的问题。
答案 0 :(得分: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)
以下情况如何?
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;
}
变化是:
"Please type in a sentence: "
以重新打印。strInput
是否是“q”并在打印之前退出,即不需要打印“q”,还是在那里?println
打印已加扰的strInput
,以便下一行显示下一个"Please type in a sentence: "
,并且光标与" ... sentence: "
显示在同一行,因为 由System.out.print
(无ln
)