gpt4 book ai didi

java - 如何让JOptionPane计算面积?

转载 作者:行者123 更新时间:2023-12-02 03:18:17 35 4
gpt4 key购买 nike

我已经创建了这段代码,GUI 弹出并且工作正常,但面积计算不正确。有什么线索吗?我对 Java 编码非常陌生,因此非常感谢您的帮助。提前致谢。

package pkg4.pkg2.pkgnew.project;

import javax.swing.JOptionPane;

public class NewProject {

public static void main(String[] args) {

String inputStr = JOptionPane.showInputDialog("Type 1 for the area of Triangle, 2 for area of Circle, 3 for Rectangle, and 0 for area of none of these.");

int i = Integer.parseInt(inputStr);
if (i == 1) {
String input = JOptionPane.showInputDialog("Enter the first value to calculate the area of a triangle: ");
int n1 = Integer.parseInt(inputStr);
String inp = JOptionPane.showInputDialog("Enter the second value to calculate the area of a triangle: ");
int n2 = Integer.parseInt(inputStr);
areaTriangle(n1, n2);
}
if (i == 2) {
String inpu = JOptionPane.showInputDialog("Enter a value to calculate the area of a circle: ");
double radius = Integer.parseInt(inputStr);
areaCircle(radius);
}
if (i == 3) {
String inp = JOptionPane.showInputDialog("Enter the first value to calculate the area of a rectangle: ");
int m1 = Integer.parseInt(inputStr);
String inp2 = JOptionPane.showInputDialog("Enter the second value to calculate the area of a rectangle: ");
int m2 = Integer.parseInt(inputStr);
areaRectangle(m1, m2);
} else {
return;
}
}

public static void areaTriangle(int n1, int n2) {
int areat = (n1 * n2) / 2;
JOptionPane.showMessageDialog(null, "The area of a triangle with your values is: " + areat);
}

public static void areaCircle(double radius) {
double areac = Math.PI * (radius * radius);
JOptionPane.showMessageDialog(null, "The area of a circle with your value is: " + areac);
}

public static void areaRectangle(int m1, int m2) {
int arear = (m1 * m2);
JOptionPane.showMessageDialog(null, "The area of a rectangle with your values is: " + arear);

}

public static void calcArea(int x) {

}
}

最佳答案

代码的问题在于,每次将输入解析为字符串时,您始终使用该字符串的相同值。每次调用函数时,您都会在区域函数调用中使用所有 1、2 或 3 作为参数。因此,您需要更改 Integer.parseInt() 以包含从用户那里获得的新字符串,如下所示:

 String input = JOptionPane.showInputDialog("Enter the first value to calculate the area of a triangle: ");
int n1 = Integer.parseInt(input); //not inputStr <----------
String inp = JOptionPane.showInputDialog("Enter the second value to calculate the area of a triangle: ");
int n2 = Integer.parseInt(inp);//not inputStr <---------
areaTriangle(n1, n2);

关于java - 如何让JOptionPane计算面积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40002784/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com