在输出的下一行获取输入

Getting an input on the next line of an output

基本上我试图让我的代码输出给定的变量(由用户输入提供)以显示在我的输出下面的一行中。

例如,我的代码是这样做的:

    Enter 3 variables for array X:
    2.1
    3.5
    5.4

我希望它这样做:

    Enter 3 variables for array Y:
    2.1 3.5 5.4

这是我的全部代码:

import java.util.Scanner;
public class Project4JamesVincent {
   public static void main(String []args){
     Scanner input = new Scanner(System.in);
     System.out.print("Enter the size of the arrays: ");
     int size = input.nextInt();
     System.out.println();
     System.out.println("Enter " + size + " items for array X: ");
     double[] arrayX = createArray(size, input);
     System.out.println();
     System.out.println("Enter " + size + " items for array Y: ");
     double[] arrayY = createArray(size, input);
     System.out.print("The distance between x and y is: ");
     double totalDistance = 0;
     for (int i = 0; i<size; i++){
        totalDistance = totalDistance + Math.abs((arrayX[i]-arrayY[i]));
     }
     double averageDistance = 0;
     averageDistance = (totalDistance/size);
     System.out.printf("%3.2f", averageDistance);
   }    
   public static double[] createArray (int n, Scanner enter){
       double[] tempArray = new double[n];
       for (int i=0; i<tempArray.length; i++){
           tempArray[i] = enter.nextDouble();
       }
       return tempArray;
   }
}

感谢任何帮助。

如果将 createArray 函数更改为此,您可以每行输入一个数字或全部输入一行:

public static double[] createArray (int n, Scanner enter){
    double[] tempArray = new double[n];
    int pos=0;
    while (enter.hasNext()) {
        tempArray[pos++] = enter.nextDouble();
        if (pos>=n)
            break;
    }
    return tempArray;
}