对于 Java 来说非常陌生,我希望更改以下内容以允许相同的变量调用仅发生一次。
第二个“b”变量仅在矩形和三角形期间被调用。这确实有效,只是想看看我是否可以从主干线中取出一行额外的线。
“b”变量无法从 if 语句中移出,因为用户只会输入 a 变量,因此程序将无法启动。
import java.util.*;
public class Main {
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
System.out.print("? ");
String word = in.next();
Shape s = null;
while (!word.equals("quit")) {
double a = in.nextDouble();
if (word.equals("triangle")){
double b = in.nextDouble();
s = new Shapet (a, b);
}else if (word.equals("rectangle")){
double b = in.nextDouble();
s = new Shaper (a, b);
}else if (word.equals("square")){
s = new Shapes (a);
}else if (word.equals("circle")){
s = new Shapec (a);
}else if (word.equals("pentagon")){
s = new Shapep (a);
}
System.out.printf("Area of %s = %.2f\n", s, s.area());
System.out.print("? ");
word = in.next();
}
}
}
最佳答案
您可以使用 switch,这不会使代码更短但更具可读性:
String word = in.next();
Shape s = null;
while (!word.equals("quit")) {
double a = in.nextDouble();
switch(word) {
case "triangle":
s = new Shapet (a, in.nextDouble());
break;
case "rectangle":
s = new Shaper (a, in.nextDouble());
break;
case "square":
s = new Shapes (a);
break;
case "circle":
s = new Shapec (a);
break;
case "pentagon":
s = new Shapep (a);
break;
}
word = in.next();
}
关于Java压缩一些代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32242254/