首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BlueJ中的距离

BlueJ中的距离
EN

Stack Overflow用户
提问于 2015-09-18 00:24:24
回答 1查看 984关注 0票数 1

输出应该如下所示:

代码语言:javascript
复制
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,如果你想找到距离的话。

,下面是我的代码现在的样子:

代码语言:javascript
复制
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");
    }
   }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-18 00:34:41

所以..。首先,不要说int要像那样加倍--进入文档,您就会发现input.nextDouble()存在,您可以直接使用它。

e.x.:

代码语言:javascript
复制
int y2 = input.nextInt();
double g = y2;
to...
double g = input.nextDouble()

此外,在您的距离公式中,您使用的是:

代码语言:javascript
复制
double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)*(y1 - y2));

如果您正在使用,请将双打命名为正确名称(x1x2等.)

当您使用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)进行评估。

试着抓住例子:

代码语言:javascript
复制
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语句评估斜率:

代码语言:javascript
复制
if(slope > 0)
System.out.println("Positive slope")
else if(slope == 0)
System.out.println("Flat slope")...

希望你有这个想法。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32642011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档