2014-11-16 51 views
0

我的任務包括:我必須設計一個計算器,允許用戶輸入三角形的數量。目標如下:三角形側面和角度分類生成器

- 用戶進入三角形

- 計算機自動地從圖3和13

- 計算機在屏幕上顯示這些數字之間我的號碼列表生成3個數字的x個。

- 它決定數字是否代表有效三角形的邊。 (例如,5,5和13不會創建三角形)。

- 如果數字不代表有效三角形,顯示錯誤消息

- 如果號碼是有效的,程序確定,並顯示

a)所述三角形的邊分類 - 等邊,等腰三角形,或斜角肌,和

b)該三角形的角分類 - 右,急性或鈍

[這是我做的事,但似乎已經錯了,因爲計算機只顯示「急性」 ,或「無效」。]

公共類triangle_creator擴展javax.swing.JFrame中{

private static int side1 = (int) (11 * Math.random() + 3); 
private static int side2 = (int) (11 * Math.random() + 3); 
private static int side3 = (int) (11 * Math.random() + 3); 
private static int userNum; 
private static String userInput; 

private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {             
    //get number of triangles by user in amountInput field 

    userInput=amountInput.getText(); 
    side1=Integer.parseInt(userInput); 
    side2=Integer.parseInt(userInput); 
    side3=Integer.parseInt(userInput); 

    //add all sides together 

    int sumTriangle= side1+ side2+ side3; 

    // generate error message 

    if(side1+ side2< side3){ 
     outputArea.setText("Not valid"); 
    } 
    else{ 
     if (side1==side2 && side1==side3 && side2==side3) 
      outputArea.setText("Equilateral"); 
     if (sumTriangle==sumTriangle) 
      outputArea.setText("Isosceles"); 
     if (side1!=side2&& side1!=side3&& side2!=side3) 
      outputArea.setText("Scalene"); 

    if (side1*side1+ side2*side2==side3*side3){ 
     outputArea.setText("Triangle is right"); 
    }   

    else if (side3*side3< side1*side1+ side2*side2) 
     outputArea.setText("Triangle is acute"); 

    else if (side3*side3> side1*side1+ side2*side2){ 
     outputArea.setText("Triangle is obtuse"); 

    } 

    else 
     outputArea.setText("Error"); 

}

我真的很感激,如果你們可以給我如何至少一個尖做這個工作。 Thaaanks! :)

+0

您確定此代碼曾寫過「無效」嗎? – Henry

+0

@亨利是的,只有「無效」和「三角形是尖銳的」當我運行程序並輸入了三角形的數量,並點擊計算時,它只顯示了這兩個單詞中的一個 –

+0

如果你用調試器,你會立即看到你爲什麼沒有得到你期望的結果。 –

回答

0

您的問題是,side1,side2side3都設置爲相同的值,即由Integer.parseInt(userInput)返回的值。

在大多數情況下,有什麼未來會是side1+ side2< side3會是假的,那麼代碼進入else塊。現在評估了很多條件,最終將對side3*side3< side1*side1+ side2*side2進行評估,結果爲true,因此將顯示"Triangle is acute"

但是,如果你在字段中輸入一個足夠大的值,可以評估side1+ side2< side3時得到整數溢出 - 即side1 + side2可能太大,不適合到int領域,所以它會溢出到負值。在這種情況下,這種情況將是真實的,將會顯示"Not valid",並且將永遠不會輸入else塊。