我制作了一个程序,要求用户输入一个数字,然后检查它是否等于,小于或大于随机数。一个siple猜谜游戏。它工作得很好,但我想在输入的同一行显示输出,但我无法弄清楚如何做到这一点。
Ok, I've picked a number between 1 and 100. What is your first guess?
Guess 1: 36
<
Guess 2: 50
>
Guess 3: 46
That is correct. The hidden number is 46.
这就是我希望它的样子:
Guess 1: 36 <
Guess 2: 50 >
Guess 3: 46 That is correct. The hidden number is 46.
我该怎么做?当我使用Scanner.nextInt();
这是我目前的代码:
while (!isCorrect) {
System.out.print("Guess " + guessCount + ": ");
currentGuess = input.nextInt();
if (currentGuess == randomNumber) {
isCorrect = true;
System.out.println("That is correct. The hidden number was " + randomNumber);
}
else if (currentGuess > randomNumber) {
System.out.println(" >");
++guessCount;
}
else if (currentGuess < randomNumber) {
System.out.println(" <");
++guessCount;
}
}
答案 0 :(得分:0)
这不是一贯可能的。您可以尝试回显\b
退格符,但这可能不起作用。一旦用户键入新行,就无法将其删除。
答案 1 :(得分:0)
你能够完成的最好的事情就是重新回应输入。
while (!isCorrect) {
System.out.print("Guess " + guessCount + ": ");
currentGuess = input.nextInt();
if (currentGuess == randomNumber) {
isCorrect = true;
System.out.println("That is correct. The hidden number was " + randomNumber);
}
else if (currentGuess > randomNumber) {
System.out.println(currentGuess + " >");
++guessCount;
}
else if (currentGuess < randomNumber) {
System.out.println(currentGuess + " <");
++guessCount;
}
}
输出:
Guess 1: 36 36 < Guess 2: 50 50 > Guess 3: 46 That is correct. The hidden number is 46.
答案 2 :(得分:0)
如果您确实需要格式化输出,可以尝试将输入保存到arraylist,清除屏幕,然后再将所有先前输入打印到屏幕。
List<Integer> foo = new ArrayList<Integer>();
while (!isCorrect) {
System.out.print("Guess " + guessCount + ": ");
guessCount++;
currentGuess = input.nextInt();
foo.add(currentGuess);
for(int a = 0; a < 50; a++) {
System.out.println('\n');
}
for(int i = 0; i < foo.size(); i++) {
currentGuess = foo.get(i);
System.out.print("Guess " + (i+1) + ": " + currentGuess);
if (currentGuess == randomNumber) {
isCorrect = true;
System.out.println(" That is correct. The hidden number was " + randomNumber);
}
else if (currentGuess > randomNumber) {
System.out.println(" >");
}
else if (currentGuess < randomNumber) {
System.out.println(" <");
}
}
}
要清除屏幕,我刚打印出50个空行。
此处提出了清除控制台的解决方案: Java: Clear the console 但是,它对我或克里斯不起作用。