簡體   English   中英

處理 Java 中的無效輸入

[英]Handling invalid inputs in Java

我有一個名為Line的類,我想添加一個計算線切線的方法。 要計算切線,我需要兩個點:(x1,y1) 和 (x2,y2),因此它們的切線將為 (y2 - y1) / (x2 - x1)。 假設我有兩個點,我想計算切線,在某些情況下,切線未定義(x2 = x1),線平行於 y 軸)。 我希望能夠使用這個函數,當它得到一條沒有切線的線時,程序不會崩潰,只是顯示一個錯誤。 我該怎么做?

這是函數(它在一個名為Line的類中):

double getTangent() {
    // defined only if the line is not perpendicular to the horizontal axis.
    return (this.end.getY() - this.start.getY()) / (this.end.getX() - this.start.getX());
}

這是可以接受的嗎?

double getTangent() {
    if (this.end.getY() == this.start.getY()) {
        return 0;  // line is parallel to x-axis
    }
    else if (this.end.getX() == this.start.getX()) {
        return Double.NaN; // line is parallel to y-axis, i.e. undefined
    }
    else {
        return (this.end.getY() - this.start.getY()) / (this.end.getX() - this.start.getX());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM