编写一个程序,提示用户输入两个点(包括工作)

时间:2014-02-10 22:39:41

标签: java

编写一个程序,提示用户输入两个点(x1,y1)和(x2,y2)并显示它们之间的距离。计算距离的公式为:(x2-x1)^ 2 +(y2-y1)^ 2的平方根

这就是我所拥有的:

import java.util.Scanner;

public class TwoPoints {
    private static double x;
    private static double distance;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter first two points (x1,y1) :");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();

        System.out.print("Enter second two points (x2,y2) :");
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();
        x = ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));


        distance = Math.sqrt(x);
        System.out.print("The distance of the two points is " + distance);

然而:

我一直收到以下错误:

Enter first two points (x1,y1) :4,2
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at TwoPoints.main(TwoPoints.java:23)

Java Result: 1

BUILD SUCCESSFUL (total time: 4 seconds)

请帮忙。感谢

3 个答案:

答案 0 :(得分:2)

解释在Scanner javadoc的第二句中:

  

扫描程序使用分隔符模式将其输入分解为标记,分隔符模式默认匹配空格。

逗号不是空格,,2不是有效的双精度空格。

答案 1 :(得分:0)

4(输入)2(输入)(两个)整数

或4.2(带点)如果你想要实数

答案 2 :(得分:0)

您使用逗号分隔值,这会破坏Scanner类。试试这个,它使用BufferedReader和split()来分隔逗号分隔值:

public static void main(String[] args) throws IOException {
    System.out.print("Enter first coordinates: ");
    String[] firstCoords = new BufferedReader(new InputStreamReader(
        System.in)).readLine().split(",");
    double x1 = Double.valueOf(firstCoords[0]);
    double y1 = Double.valueOf(firstCoords[1]);

    System.out.print("Enter second coordinates: ");
    String[] secondCoords = new BufferedReader(new InputStreamReader(System.in)).readLine().split(",");
    double x2 = Double.valueOf(secondCoords[0]);
    double y2 = Double.valueOf(secondCoords[1]);

    double result = Math.sqrt(((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)));
    System.out.println(String.valueOf(result));
    }

输出:

Enter first coordinates: 6,7
Enter second coordinates: 0,0
9.219544457292887