Java压缩一些代码

标签 java variables optimization

对于 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/

相关文章:

MySQL优化连接查询 "OR"条件

java - 如何在 Java 代码中保留 C++ 对象?可能的?

java - 如何使用 RxJava 和 Spring 进行批量保存

java - 用 Java 创建动态搜索框/表格

c++ - 这个局部变量的声明实际上会重复很多次吗?

algorithm - 在数组中查找小于给定索引处数字的最近索引号

Java:使用计时器进行测验

ios - 从 UITableViewCell 分配变量以在主视图 Controller 中发送推文

Javascript 将 dom 对象定义为变量

haskell - 比较 ghc 中生成的代码