输出应该如下所示:
Enter the x and y coordinates of the first point: 3 -2
Enter the x and y coordinates of the second point: 9 2
Distance: 7.211
Positive Slope我已经用代码应该是什么样子更新了OP,如果你想找到距离的话。
,下面是我的代码现在的样子:
import java.util.Scanner;
public class LineEvaluator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the x and y coordinates of the first point: ");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
System.out.print("Enter the x and y coordinates of the second point: ");
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
System.out.printf("Distance: %.3f", distance);
double slope = ((y2 - y1) / (x2 - x1));
if(slope > 0)
System.out.println("Positive Slope");
else if(slope < 0)
System.out.println("Negative Slope");
else if(slope == 0)
System.out.println("Horizontal");
}
}发布于 2015-09-18 00:34:41
所以..。首先,不要说int要像那样加倍--进入文档,您就会发现input.nextDouble()存在,您可以直接使用它。
e.x.:
int y2 = input.nextInt();
double g = y2;
to...
double g = input.nextDouble()此外,在您的距离公式中,您使用的是:
double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)*(y1 - y2));如果您正在使用,请将双打命名为正确名称(x1、x2等.)
当您使用int时,它会截断。阅读差异:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
然后,您可以计算斜率,比如将其存储在变量slope中。
当您试图找到具有无限斜率的斜率时,您将得到以下错误:ArithmeticException。
您可以通过一个try catch来修复这个问题,围绕着您可能除以0的代码,然后在这种情况下进行System.out.println("Vertical Line"),或者您可以稍后进行计算并将try catch保留为空白。稍后使用这个:Double.isInfinite(double)进行评估。
试着抓住例子:
try{
slope = (y2-y1)/(x2-x1)//if it's divide by zero then we will get this error
}catch(ArithmeticException e){
//Take care of the error as we discussed.
}使用if-else或switch语句评估斜率:
if(slope > 0)
System.out.println("Positive slope")
else if(slope == 0)
System.out.println("Flat slope")...希望你有这个想法。
https://stackoverflow.com/questions/32642011
复制相似问题