import javax.swing.JOptionPane;
public class Shapes {
static String shape;
static String circleInput;
static String c;
static String r;
static String t;
static double radius;
public static void main(String[] args) {
// Creation of all three shape objects
Circle circleSolution = new Circle();
Rectangle solution2 = new Rectangle(shape, r);
Triangle solution3 = new Triangle(shape, t);
String choice = "y";
// Creation of a while loop which continues when 'choice' is 'y'
while (choice.equalsIgnoreCase("y")) {
// Prompts user for a shape or the interger 1 to end the program.
shape=
JOptionPane.showInputDialog ("Enter one of the following shapes:"
+ " circle, rectangle or triangle.");
// Converts the String 'shape' into an interger
if (shape.equalsIgnoreCase("circle")) {
shape = c;
circleInput = JOptionPane.showInputDialog ("Enter the radius.");
radius = Math.abs(Integer.parseInt(circleInput));
JOptionPane.showMessageDialog (
null, "The area of the circle is " + circleSolution.getCircleArea(), "Results",
JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog (
null, "The perimeter of the circle is " + circleSolution.getCirclePerimeter(), "Results",
JOptionPane.PLAIN_MESSAGE);
}
else if (shape.equalsIgnoreCase("rectangle")) {
shape = r;
// Prompts user for pertinent data
}
else if(shape.equalsIgnoreCase("triangle")) {
shape = t;
}
}
Circle對象類
public class Circle {
// Circle object created
Shapes circle = new Shapes();
// Defines variables used in class
private static String shape;
private static double radius;
private static String circleInput;
private static String c;
// Constructor for circles, with arguments
Circle() {
shape = Shapes.shape;
radius = Shapes.radius;
circleInput = Shapes.circleInput;
c = Shapes.c;
}
// Instance method used to return the shape
public String getShape() {
return shape;
}
// Instance method used to return the value of the circle's radius
public double getRadius() {
return radius;
}
// Instance method used return the string, circleInput
public String getCircleInput() {
return circleInput;
}
// Instance method used to return the specific shape
public String getC() {
return c;
}
double getCircleArea() {
double circleArea = Math.PI * radius * radius;
return circleArea;
}
double getCirclePerimeter() {
double circlePerimeter = 2 * Math.PI * radius;
return circlePerimeter;
}
}
至於圓形的兩個面積和周長,我得到一個0.0的結果。顯然,這是不希望的。
如果您有任何疑問,請一定要問。
任何和所有幫助/建議將不勝感激,在此先感謝!
我的魔球是說,你做了一些錯誤;) –
爲什麼要使用靜態字段? –
你是如何通過半徑的價值。要麼你必須通過方法參數或重新定義你的構造函數採取它。 – yogidilip