2015-11-02 27 views
-3

有人可以幫我找出錯誤嗎?我似乎無法弄清楚這個主代碼有什麼問題。爲了補充細節,我會給出第二個。我收到的錯誤是:StackOverflowError:null

java.lang.StackOverflowError: 
null 

主要代碼:

public class Line 
{ 
private int x1, y1, x2, y2; 
private double Slope; 

public Line(int a1, int b1, int a2, int b2) 
{ 
    Line test = new Line(a1, b1, a2, b2); 
} 

public void setCoordinates(int a1, int b1, int a2, int b2) 
{ 
    a1=x1; 
    b1=y2; 
    a2=x2; 
    b2=y2; 
} 

public void calculateSlope() 
{ 
    Slope = (x2-x1)/(y2-y1); 
    Slope = (double)Slope; 
} 

public void printSlope() 
{ 
    System.out.printf("The slope is %.2f" , Slope); 
} 
} 

二級密碼:

public class LineRunner 

{ 
public static void main(String[] args) 
    { 

    Line test = new Line(1, 9, 10, 11); 
    test.calculateSlope(); 
    test.printSlope(); 

    test= new Line (1, 7, 18, 3); 
    test.calculateSlope(); 
    test.printSlope(); 

    test = new Line(6, 4, 2, 2); 
    test.calculateSlope(); 
    test.printSlope(); 

    test = new Line(4, 4, 5, 3); 
    test.calculateSlope(); 
    test.printSlope(); 

    test = new Line(1, 1, 2, 9); 
    test.calculateSlope(); 
    test.printSlope(); 

    } 
} 
+1

請在發佈的代碼中擺脫所有不必要的和分散注意力的空白。一個空白行在任何一個地方都綽綽​​有餘。 –

+2

這不是你得到的錯誤。 Java錯誤伴隨着一道信息牆。給我們那面牆,或者至少是那面牆的開始。 – Teepeemm

+1

雖然給出的答案是正確的,但我想指出的是,您的'calculateSlope'方法將執行整數除法,因此不會像您想要的那樣產生精確的數字。將它分配給「(x2-x1)/(double)(y2-y1)」應該給你一個更精確的數字,而不是分配斜率變量兩次。 –

回答

1

Line構造函數調用本身,它自稱,其自稱,這調用自己,調用自己,調用自己,自己調用自己,調用自己,這會導致StackOverflowError

Line test = new Line(a1, b1, a2, b2); 

你可能意味着它打電話setCoordinates()

setCoordinates(a1, b1, a2, b2); 

除了這是行不通的,因爲它實際上是:

public void setCoordinates(int a1, int b1, int a2, int b2) 
{ 
    a1 = this.x1; 
    b1 = this.y2; 
    a2 = this.x2; 
    b2 = this.y2; 
} 

你大概意思的其他方式分配。

+0

非常感謝。無論如何,我只是想知道是否有關鍵字「this」的替代方案? – user41854

+0

替代方法並沒有像你那樣使用它,並導致像你一樣的錯誤。總是使用'this'是一個好主意,因爲它可以幫助你的代碼讀者(和你自己)理解你指的是一個實例字段,而不是一個本地變量/參數。 – Andreas