分配多个数字输入

时间:2018-01-23 17:33:21

标签: java user-input

我试图在一行中读取多个输入并将它们分配给变量。这些输入是EDIT:ints。

我已经编写了一些可行的代码 - 但我想知道是否有更简化的方法:

我的代码:

import java.util.Scanner;

public class Distance {
    public static void main(String[] args) {
        int x1, y1, x2, y2, distance;
        String[] numbers;
        Scanner input = new Scanner(System.in);

        //getting user input
        System.out.print("Enter your first coordinate numbers separated by a space: ");
        numbers = input.nextLine().split(" ");
        x1 = Integer.parseInt(numbers[0]);
        y1 = Integer.parseInt(numbers[1]);
        System.out.print("Enter your second coordinate numbers separated by a space: ");
        numbers = input.nextLine().split(" ");
        x2 = Integer.parseInt(numbers[0]);
        y2 = Integer.parseInt(numbers[1]);

        distance = Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2));
        System.out.printf("%.3f", distance);

    }

}

正如您所看到的,我的方法涉及获取字符串数组并从数组中分配双精度数。这项工作,我的计划将被接受。但是对于我自己的个人发展,我想知道是否可以让用户输入两个(或更多)数字并将它们分配给变量而不用我采取的所有额外步骤。

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

public class InputTest {
    public static void main(String[] args) {
        double x1, y1, x2, y2, distance;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your first coordinate numbers separated by a space: ");
        x1 = input.nextDouble();
        y1 = input.nextDouble();
        System.out.print("Enter your second coordinate numbers separated by a space: ");
        x2 = input.nextDouble();
        y2 = input.nextDouble();
        distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
        System.out.printf("%.3f", distance);

    }
}