Java - 在同一控制台行上获取用户输入

时间:2018-02-04 15:02:42

标签: java console

作为一项训练练习,我必须接受用户输入以进行猜测,其中包含4个整数。到目前为止,我已经写过:

// IV. The computer asks the user to guess the 4-tuples. The user input must
// be in the same line as the question, a space between each two numbers, and 
// an enter after the last one (as shown in the example).

System.out.print("Iteration 1. Next guess: ");
int Guess1 = x.nextInt();
System.out.print(" ");
int Guess2 = x.nextInt();
System.out.print(" ");
int Guess3 = x.nextInt();
System.out.print(" ");
int Guess4 = x.nextInt();
System.out.println(" ");

输出是接收,但是如下:

Iteration 1. Next guess: 1    
2    
2   
2

即使我正在使用" print"功能而不是" println"函数,当用户给出输入时,它似乎转到下一行。是否有任何想法确保输入数字显示在同一行的控制台中?像这样:

Iteration 1. Next guess: 1 2 2 2

2 个答案:

答案 0 :(得分:4)

输入空格输入:

System.out.print("Iteration 1. Next guess: ");
  int Guess1 = x.nextInt();
  int Guess2 = x.nextInt();
  int Guess3 = x.nextInt();
  int Guess4 = x.nextInt();

答案 1 :(得分:1)

暂时不要担心用户输入格式,在高级培训中,您将使用 GUI 与用户进行交互。

现在。 将您的输入添加到以空格分隔的单行中。系统将识别这些数字并忽略空格。添加四个数字后,按Enter键。 删除System.out.print("")