Java中是否有一种方法可以确保当用户输入一个值时,后续输出出现在同一行,直接与输入提示相邻,而不需要移动到新行?换句话说,我们能否实现输入和输出在同一行显示的设置?
期望:
Factorial of 5: 120
现实:
Factorial of 5
: 120
以下是参考代码:
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int total = 1;
int i;
System.out.print("Factorial of ");
int input = s.nextInt();
for (i = 1; i <= input; i++) {
total *= i;
}
System.out.print(": " + total);
}
}
你在作弊,这不是可能导致你给出的输出的代码。您的代码永远不会在控制台中输出5。要获得结果,您需要 System.out.println(input),这就是导致新行的原因。