Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 分配多个数字输入_Java_User Input - Fatal编程技术网

Java 分配多个数字输入

Java 分配多个数字输入,java,user-input,Java,User Input,我试图在一行中读取多个输入,并将它们分配给变量。这些输入是EDIT:int 我已经编写了一些代码,但我想知道是否有一种更为精简的方法可以做到这一点: 我的代码: import java.util.Scanner; public class Distance { public static void main(String[] args) { int x1, y1, x2, y2, distance; String[] numbers; S

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

我已经编写了一些代码,但我想知道是否有一种更为精简的方法可以做到这一点:

我的代码:

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);

    }

}
如您所见,我的方法涉及获取字符串数组并从数组中分配双精度。这是有效的,我的计划将被接受。但为了我个人的发展,我想知道是否有可能让用户输入两个(或更多)数字并将它们分配给变量,而不需要我采取所有额外的步骤。

尝试以下代码:

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);

    }
}

检查-有多种方法可以收集不需要解析字符串的用户输入。此外,变量是双精度的,但代码使用
Integer.parseInt()
。似乎应该将其更改为
Double.parseDouble()
。将Double编辑为int-这是我在键入时的错误。如果将其更改为int,则需要转换距离,它将不支持此格式。我不明白它是如何工作的,但它是如何工作的。非常感谢。我需要阅读一行中的输入如何在没有任何进一步说明的情况下分解为两个变量。基本上,scanner类将一直请求输入,直到调用其
nextXXX()
方法为止