我需要协助我的Java程序分配。赋值是使用java计算两点之间的距离。我完成了第一部分:
import java.util.Scanner;
public class DistanceCalcEasy
{
public static void main(String[] args)
{
// Creating a new scanner object
System.out.println("Distance Calculator");
Scanner input = new Scanner(System.in);
// Getting all of the coordinates
System.out.print("Enter the X coordinate of the first point: ");
double x1 = input.nextDouble();
System.out.print("Enter the Y coordinate of the first point: ");
double y1 = input.nextDouble();
System.out.print("Enter the X coordinate of the second point: ");
double x2 = input.nextDouble();
System.out.print("Enter the Y coordinate of the second point: ");
double y2 = input.nextDouble();
// Calculating the distance between the points
double distance = Math.sqrt( Math.pow((x2-x1),2) + Math.pow((y2-y1),2) );
// Printing the distance to the User
System.out.println("The distance between the points is " + distance);
}
}
现在的问题是我需要再次执行相同的程序,但是通过允许用户输入像1,2这样的坐标而不是每个x和y在自己的行上的“硬路”。这是我在经过一些研究后开始提出的:
import java.util.Scanner;
public class DistanceCalcHard
{
public static void main(String[] args)
{
// Creating a new Scanner Object
System.out.println("Distance Calculator");
Scanner input = new Scanner(System.in);
// Getting the data points
System.out.print("Enter the first point x,y: ");
String firstPoint = input.nextLine();
System.out.print("Enter the second point x,y: ");
String secondPoint = input.nextLine();
Scanner scan = new Scanner(firstPoint).useDelimiter("\\s*,\\s*");
while (scan.hasNextDouble() )
{
}
// Calculating the distance
// Displaying the distance to the user
}
}
这似乎是一个好的开始吗?我以为我可以制作两个阵列,每个点一个,然后以这种方式进行距离计算。有没有更简单的方法来做到这一点,或者有人能指出我更好的方向?谢谢
答案 0 :(得分:1)
将字符串拆分为两个值(即x,y - > x和y)的更简单方法是使用split()
运算符作为String
对象。
String[] pointA = firstPoint.split(",");
第二点也可以这样做。现在,您在阵列中得到两点,其中pointA[0]
是x值,pointA[1]
是y值。
可以找到有关该方法的更多文档here
答案 1 :(得分:0)
这样的事情怎么样:
import java.util.Scanner;
public class DistanceCalcEasy
{
public static void main(String[] args)
{
// Creating a new scanner object
System.out.println("Distance Calculator");
Scanner input = new Scanner(System.in);
// Getting all of the coordinates
System.out.print("Enter the X,Y coordinate of the first point: ");
String xy1in = input.nextLine();
System.out.print("Enter the X,Y coordinate of the second point: ");
String xy2in = input.nextLine();
String[] xy1 = xy1in.split(",");
String[] xy2 = xy2in.split(",");
double x1 = Double.parseDouble(xy1[0]);
double y1 = Double.parseDouble(xy1[1]);
double x2 = Double.parseDouble(xy2[0]);
double y2 = Double.parseDouble(xy2[1]);
// Calculating the distance between the points
double distance = Math.sqrt( Math.pow((x2-x1),2) + Math.pow((y2-y1),2) );
// Printing the distance to the User
System.out.println("The distance between the points is " + distance);
}
}