我有這個作業,我必須使用JOptionPane
來計算不同形狀的面積,但是當我使用JOptionPane.showMessageDialog
時,它會變成紅色,錯誤代碼表示void
不能轉換爲int
。有人可以幫我弄清楚如何使用JOptionPane.showMessageDialog
?爲什麼我用JOptionPane.showInputDialog得到「void無法轉換爲int」錯誤?
public static void areaTriangle(int base, int height)
{
System.out.println(0.5 * base * height);
}
public static void areaCircle(int radius, double area)
{
area = Math.PI * (radius * radius);
System.out.println(area);
}
public static void areaRectangle(int length, int width)
{
System.out.println(length * width);
}
public static void calcArea()
{
System.out.println("What type of area do you want to calculate?");
inputStr = JOptionPane.showInputDialog("Type 1 for triangle, 2 for circle, 3 for rectangle, and 0 for none, then press ENTER.");
int type = Integer.parseInt(inputStr);
if (type == 0)
{
return;
}
else if (type == 1)
{
inputStr = JOptionPane.showInputDialog("Enter the measurement of the base, then press ENTER.");
int base = Integer.parseInt(inputStr);
inputStr = JOptionPane.showInputDialog("Enter the measurement of the height, then press ENTER.");
int height = Integer.parseInt(inputStr);
int areaT = areaTriangle (base, height);
JOptionPane.showMessageDialog(null, "The area of the triangle is: " + areaT);
}
else if (type == 2)
{
inputStr = JOptionPane.showInputDialog("Enter the measurement of the radius, then press ENTER.");
int radius = Integer.parseInt(inputStr);
double area = Math.PI * (radius * radius);
int areaC = areaCircle (radius, area);
JOptionPane.showMessageDialog(null, "The area of the cicle is: " + areaC);
}
else if (type == 3)
{
inputStr = JOptionPane.showInputDialog("Enter the measurement of the length, then press ENTER.");
int length = Integer.parseInt(inputStr);
inputStr = JOptionPane.showInputDialog("Enter the measurement of the width, then press ENTER.");
int width = Integer.parseInt(inputStr);
int areaR = areaRectangle(length, width);
JOptionPane.showMessageDialog(null, "The area of the rectangle is: " + areaR);
}
}
public static void main(String[] args)
{
calcArea();
}
請詳細說明問題的具體位置。看看你的代碼,當你做「int areaT = areaTriangle(base,height);因爲您將該方法的返回類型定義爲void,並嘗試將其分配給一個整數。 – bgse