1

我在 Java 中的笛卡尔斜率计算遇到了一些问题。所以我的源代码让你输入 4 个数字,x1 y1 x2 y2,它们代表笛卡尔坐标系中 2 个点的 2 个坐标。

然后我通过计算 deltaX 和 deltaY 来计算斜率。(deltaY / deltaX)所以如果你得到一个数字的十分之一,我会使用双精度来计算斜率末端。

然后我用一个 IF 函数说:if slope = 0 --> println("not a linear line"). 否则计算 X 和 Y 极的交叉点并打印结果

所以问题来了:如果斜率为 0(例如 x1:0 y1:1 x2:0 y2:9),那么我会得到一个错误:Exception in thread main java.lang.ArithmeticException: / by zero


这是完整的脚本:

import java.io.*;

public class Cartesian
{
    public static int leesIn(String var, BufferedReader in) throws IOException
    {
        System.out.println("type een getal in die " + var + " moet voorstellen.");
        return Integer.parseInt(in.readLine());
    }
    public static void main(String[] args) throws IOException
    {


    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    int x1, x2, y1, y2;
    x1 = leesIn("X1", in);
    y1 = leesIn("Y1", in);
    x2 = leesIn("X2", in);
    y2 = leesIn("Y2", in);

    System.out.println("The Coördinates of point 1 is: (" + x1 + ", " + y1 + "). The Coördinates of point 2 is: (" + x2 + ", " + y2 + ").");


    int deltaY = y2 - y1;
    int deltaX = x2 - x1;
    double RC = deltaY / deltaX;

    if ((RC) == 0)
    {
        System.out.println("The slope is 0, no linear line.");
    }else
    {
        System.out.println("The slope is: " + RC);
        double B = y1-(RC*x1);
        System.out.println("The crosspoint with Y, if x is 0, : " + B);
    }
}
}

有人知道如何解决我的问题吗?提前tnx!

4

3 回答 3

1

做一个 try catch 块

double RC;
try{
  RC = deltaY / deltaX;

}

catch(ArithmeticException ex){
System.out.println("Not a Linear Line");

}
于 2013-10-18T10:20:16.533 回答
1

您应该将计算移到您确定可以计算的区域(在您的情况下)double RC = deltaY / deltaX;

所以你的代码将是:

int deltaY = y2 - y1;
int deltaX = x2 - x1;

if (deltaY == 0)
{
    System.out.println("The slope is 0, no linear line.");
}else if (deltaX == 0)
{
    System.out.println("Not a Linear Line");
}else
{
    double RC = (double) deltaY / deltaX;
    System.out.println("The slope is: " + RC);
    double B = y1-(RC*x1);
    System.out.println("The crosspoint with Y, if x is 0, : " + B);
}
于 2013-10-18T10:22:28.560 回答
0

试试这个

try {

  double RC = deltaY / deltaX;

  if ((RC) == 0)
  {
    System.out.println("The slope is 0, no linear line.");
  }else
  {
    System.out.println("The slope is: " + RC);
    double B = y1-(RC*x1);
    System.out.println("The crosspoint with Y, if x is 0, : " + B);
  }
} catch(ArithmeticException ae) {
    System.out.println("Not a linear line");
}
于 2013-10-18T10:30:32.527 回答