所以我已经在这段代码上工作了一段时间了,这让我有些失落。请记住,我是Java的新手,所以我对Java的使用有点慢。我创建了一些形状类,这些类实现了与getArea,getPerimeter和getDescription方法的接口。有多种形状,但这并不是问题所在。当我尝试实现开关盒以允许用户选择他或她想要添加的形状时,问题就来了。由于形状数组将允许我尝试添加的形状的地址,我收到相同的消息的次数很多。我意识到我犯的错误很可能是初学者,非常感谢您的帮助,谢谢。另外,如果您能给我一个关于如何按形状的面积对形状进行分类的线索,将不胜感激。
public class ShapeApp2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Shape[] test = new Shape[10];
System.out.println("Choose a shape or type stop to break away?");
Scanner sc = new Scanner(System.in);
String Shape = sc.nextLine();
for (int i=0; i<test.length; i++) {
switch (Shape) {
case "Rectangle":
System.out.println("You have chosen a Rectangle");
test[i] = new Rectangle();
System.out.println("Enter another one now");
break;
case "Square":
System.out.println("You have chosen a Square");
test[i] = new Square();
System.out.println("Enter another one now");
break;
case "Equilateral Triangle":
System.out.println("You have chosen an Equilateral Triangle");
test[i] = new Equilateral_Triangle();
System.out.println("Enter another one now");
break;
case "Right Triangle":
System.out.println("You have chosen a Right Triangle");
test[i] = new Right_Triangle();
System.out.println("Enter another one now");
break;
case "Isosceles Triangle":
System.out.println("You have chosen an Isosceles Triangle");
test[i] = new Isosceles_Triangle();
System.out.println("Enter another one now");
break;
case "Scalene Triangle":
System.out.println("You have chosen a Scalene Triangle");
test[i] = new Scalene_Triangle();
System.out.println("Enter another one now");
break;
case "Stop":
break;
}
System.out.println(test[i]);
}
}
}
这里还有一些用于上下文的Shape类。
package shapeapp2;
/**
*
* @author my-pc
*/
public class Rectangle implements Shape {
private double length;
private double width;
private String shapeName;
public Rectangle(){
length = 4.0;
width = 5.0;
shapeName = "Rectangle";
}
public double getArea(){
double Area;
Area = length * width;
return Area;
}
public double getPerimeter() {
double Perimeter;
Perimeter = (2*length) + (2*width);
return Perimeter;
}
public String getDescription() {
return shapeName;
}
}
package shapeapp2;
/**
*
* @author my-pc
*/
public class Square implements Shape {
private double length;
private double width;
private String shapeName;
public Square(){
length = 8.0;
width = 8.0;
shapeName = "Square";
}
public double getArea(){
double Area;
Area = length * width;
return Area;
}
public double getPerimeter() {
double Perimeter;
Perimeter = (2*length) + (2*width);
return Perimeter;
}
public String getDescription() {
return shapeName;
}
}
答案 0 :(得分:1)
在循环之前,您仅从用户读取一次形状。您想在循环中阅读它。那是唯一有意义的事情。
String Shape = sc.nextLine();
for (int i=0; i<test.length; i++) {
应该是
for (int i=0; i<test.length; i++) {
String Shape = sc.nextLine();
此外,您应该重命名该变量。 Shape
看起来像一个类名。