2013-10-18 105 views
1

我在使用Java計算笛卡爾斜率時遇到了一些麻煩。 所以我的源代碼可以讓你輸入4個數字,x1 y1 x2 y2,它代表了笛卡爾座標系中2個點的2個座標。笛卡兒斜率計算錯誤Java

然後我通過計算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!

回答

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); 
} 
+0

Thx工作完美 – SteelDevil

+0

需要15個聲望點:( – SteelDevil

+0

大聲笑,那麼你去:) – SteelDevil

1

做一個try catch塊

double RC; 
try{ 
    RC = deltaY/deltaX; 

}

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

} 
+0

抱歉給了一個編譯器錯誤回來稍後在代碼中缺少可變RC ...所以我使用雙RC;嘗試{RC = deltaX/deltaY;}與代碼的其餘部分,它給了另一個編譯器錯誤回來:RC可能尚未初始化... – SteelDevil

+0

作出更改..現在看到它 –

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"); 
}