gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:13:21 25 4
gpt4 key购买 nike

编写一个程序,提示用户输入两个点(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)

请帮忙。谢谢

最佳答案

解释在Scanner javadoc的第二句中:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

逗号不是空格,并且 ,2 不是有效的 double 值。

关于java - 编写一个程序,提示用户输入两点(包括工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21689391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com