[JAVA]switch case default
Posted profesor
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[JAVA]switch case default相关的知识,希望对你有一定的参考价值。
public class Calculator { public static void main(String[] args) { //为了避免magic number,采取定义变量 double n1, n2; n1 = 56; n2 = 65; System.out.println(calc(n1, n2, ‘+‘)); System.out.println(calc(n1, n2, ‘-‘)); System.out.println(calc(n1, n2, ‘*‘)); System.out.println(calc(n1, n2, ‘/‘)); System.out.println(calc(n1, n2, ‘)‘)); } static double calc(double num1, double num2, char operator) { double result = 0.0; switch(operator) { case ‘+‘: result = num1 + num2; break; //注意:如果直接return num1 + num2; break; 最后的break就unreachable case ‘-‘: result = num1 - num2; break; //所以采用定义新变量result来解决 case ‘*‘: result = num1 * num2; break; case ‘/‘: result = num1 / num2; break; default: result = 0; } return result; } }
以上是关于[JAVA]switch case default的主要内容,如果未能解决你的问题,请参考以下文章