2011-03-30 98 views
0

我有一個suposed推測體積計算器和結果回來爲「0」我無法計算工作

JButton btnCalculateVlmn = new JButton("Calculate Hot Tub Volume"); 
     btnCalculateVlmn.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent arg0) 
      { 
       double width = 0, length = 0, depth = 0, volume = 0; 
       String lengthString, widthString, depthString; 
       lengthString = hotTubLengthText.getText(); 
       widthString = hotTubWidthText.getText(); 
       depthString = hotTubDepthText.getText(); 
       try 
       { 
        if (rdbtnRoundTub.isSelected()) 
        { 
         volume = Math.PI * Math.pow(length/2.0, 2) * depth; 
        } 
        else 
        { 
         volume = Math.PI * Math.pow(length * width, 2) 
           * depth; 
        } 
        DecimalFormat formatter = new DecimalFormat("#,###,###.###"); 
        hotTubVolumeText.setText("" + formatter.format(volume)); 
       } 
       catch (NumberFormatException e) 
       { 
        labelTubStatus 
          .setText("Fill in all fields"); 
       } 
      } 
     }); 
     btnCalculateVlmn.setBounds(20, 200, 180, 20); 
     hotTubs.add(btnCalculateVlmn); 
     JButton Exit = new JButton("Exit"); 
     Exit.setBounds(220, 200, 80, 20); 
     Exit.addActionListener(this); 
     hotTubs.add(Exit); 
    } 

回答

3

深度被聲明爲0,從來沒有被覆蓋......所以體積始終是0 我想你應該這樣做:

... 
double width = 0, length = 0, depth = 0, volume = 0; 
String lengthString, widthString, depthString; 
lengthString = hotTubLengthText.getText(); 
widthString = hotTubWidthText.getText(); 
depthString = hotTubDepthText.getText(); 
depth = Double.valueOf(depthString); 
length = Double.valueOf(lengthString); 
width = Double.valueOf(widthString); 
.... 
+2

和長度和寬度相同。 – Douglas 2011-03-30 13:15:28

+0

@Douglas:我不確定我是否做得對。 [code]雙倍寬度,長度,深度,音量; length = Double.valueOf(toString()); width = Double.valueOf(toString()); depth = Double.valueOf(toString());字符串lengthString,widthString,depthString; lengthString = hotTubLengthText.getText(); widthString = hotTubWidthText.getText(); depthString = hotTubDepthText.getText(); [/ code] – Mike 2011-03-30 13:32:06

+0

@Douglas:你如何在註釋中對代碼進行格式化,看起來像上面那樣?我不認爲我的通過是正確的。 – Mike 2011-03-30 13:33:33

1

你忘了字符串(lengthStringwidthStringdepthString)並將其轉換爲雙打和分配給您的變量(lengthwidthdepth)。

1

你有depth = 0

anything * 0 = 0 
0

你忘了你的字符串從輸入字段轉換翻番。

你得到0的結果,因爲你設置的長度和寬度爲0

0

在你的主要if條件兩個分支你的表情結束* depth。然而,這個depth變量似乎被設置爲0,並沒有設置爲其他任何東西。所以量將永遠是0不管你用0乘以因爲將爲0

也許你想使用depthString。像這樣:

depth = Integer.parseInt(depthString); 
if (rdbtnRoundTub.isSelected()) 
{ 
    volume = Math.PI * Math.pow(length/2.0, 2) * depth; 
} 
else 
{ 
    volume = Math.PI * Math.pow(length * width, 2) * depth; 
}