Java用switch替换if else

时间:2015-03-18 15:57:02

标签: java

我是编程新手,需要一些Java帮助。

我想转换if else语句来切换。你能帮助我吗?此外,优化该代码的最佳方法是什么? 我想学习语句之间的差异,我试图以另一种方式做错了很多......

    import java.util.Locale;

public class test {
    public static void main(String[] args) {
        Locale.setDefault(Locale.ENGLISH);

        double num1, num2, out;
        int in = Integer.parseInt(args[0]);
        num1 = Double.parseDouble(args[1]);
        num2 = Double.parseDouble(args[2]);

        if(in == 1) {
            if(args.length == 3) {
                out = num1 + num2;
                System.out.printf("%.1f + %.1f = %.1f\n", num1, num2, out);
            }
            else {
                System.out.print("wrong number of arguments");
                System.exit(0);
            }
        }
        else if(in == 2) {
            if(args.length == 3) {
                out = num1 - num2;
                System.out.printf("%.1f - %.1f = %.1f\n", num1, num2, out);
            }
            else {
                System.out.print("wrong number of arguments");
                System.exit(0);
            }
        }
        else if(in == 3) {
            if(args.length == 3) {
                out = num1*num2;
                System.out.printf("%.1f * %.1f = %.1f\n", num1, num2, out);
            }
            else {
                System.out.print("wrong number of arguments");
                System.exit(0);
            }
        }
        else if (in == 4) {
            if(args.length == 3) {
                out = num1/num2;
                System.out.printf("%.1f / %.1f = %.1f\n", num1, num2, out);
            }
            else {
                System.out.print("wrong number of arguments");
                System.exit(0);
            }
        }
        else if (in == 5){
            if(args.length >= 3) {
                double min = Double.parseDouble(args[1]);
                int ind = 1;
                for(int i=1; i<args.length; i++) {
                    if(Double.parseDouble(args[i]) <= min) {
                        min = Double.parseDouble(args[i]);
                        ind = i;
                    }
                } 
                System.out.print("minimum of numbers");
                for(int j=1; j<args.length; j++) {
                    System.out.printf("%s ", args[j]);
                }
                System.out.printf("is %s\n", args[ind]);
            }
            else {
                System.out.print("wrong number of arguments");
                System.exit(0);
            }
        }
    }
}

非常感谢!

1 个答案:

答案 0 :(得分:2)

对于像

这样的代码
if(a==1) {do1();}
else if(a==2) {do2();}
else if(a==3) {do2();}
else if(a==4) {do2();}
else { doOther(); }

等号将是

switch(a) {
    case 1: 
        do1();
        break;
    case 2: 
        do2();
        break;
    case 3: 
        do3();
        break;
    case 4: 
        do4();
        break;
    default:
        doOther();
        break;
 }