我遇到的问题是我不知道如何调用main中的方法来使它们工作。
首先,我问用户他想用什么形状计算方法中的区域" public static void userInput"。用户有3个选项可供选择。
然后有3种方法,1为圆形,1为三角形,1为方形。
public static void userInput(double radius, int base, int height, int side){
int object = Integer.parseInt(JOptionPane.showInputDialog(
"Enter 1 if you want to know the area of a circle."
\nEnter 2 if you want to know the area of a triangle.
\nEnter 3 if you want to know the area of a square"));
if (object == 1){
radius = Double.parseDouble(JOptionPane.showInputDialog("Enter the radius"));
}else if (object == 2){
base = Integer.parseInt(JOptionPane.showInputDialog("Enter the base"));
height = Integer.parseInt(JOptionPane.showInputDialog("Enter the height"));
}else if (object == 3){
side = Integer.parseInt(JOptionPane.showInputDialog("Enter the side"));
}
}
public static double circle(){
double radio = 0;
double circle = (radio * radio) * 3.14159265358;
JOptionPane.showMessageDialog(null, "The circle area is "+circle);
return circle;
}
public static int triangle(){
int base= 0;
int height= 0;
int triangle = (base * height)/2;
JOptionPane.showMessageDialog(null, "The triangle area is "+triangle);
return triangle;
}
public static int square(){
int side = 0;
int square = side * side;
JOptionPane.showMessageDialog(null, "The square area is "+square);
return square;
}
public static void main(String[] args) {
circle(userInput(radius));
triangle(userInput(base, height));
square(userInput(side));
}
有人可以推荐一个关于方法的好读物吗?
答案 0 :(得分:0)
希望这是你所寻求的:
import javax.swing.JOptionPane;
public class NewClass1 {
public void userInput(int x){
if (x == 1){
double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter the radius"));
System.out.println(circle(radius));
}else if (x == 2){
int base = Integer.parseInt(JOptionPane.showInputDialog("Enter the base"));
int height = Integer.parseInt(JOptionPane.showInputDialog("Enter the height"));
System.out.println(triangle(base,height));
}else if (x == 3){
int side = Integer.parseInt(JOptionPane.showInputDialog("Enter the side"));
System.out.println(square(side));
}
}
public static double circle(double radio){
double circle = (radio * radio) * 3.14159265358;
JOptionPane.showMessageDialog(null, "The circle area is "+circle);
return circle;
}
public static int triangle(int base,int height){
int triangle = (base * height)/2;
JOptionPane.showMessageDialog(null, "The triangle area is "+triangle);
return triangle;
}
public static int square(int side){
int square = side * side;
JOptionPane.showMessageDialog(null, "The square area is "+square);
return square;
}
public static void main(String[] args) {
NewClass1 obj = new NewClass1();
int object = Integer.parseInt(JOptionPane.showInputDialog(
"Enter 1 if you want to know the area of a circle\nEnter 2 if you want to know the area of a triangle.\nEnter 3 if you want to know the area of a square"));
obj.userInput(object);
}
}
尝试在Java方法上做一些练习。
答案 1 :(得分:0)
您在问题中粘贴的代码不完整,但根据您的问题:
从具有多个变量的方法返回值?
您可以使用类的对象返回多个变量。