• switch case什么时候用?


    第一个问题:什么时候用switch‘多分枝机构,当需要用多个if else的时候可以用switch case

    case星球score分数,支持横向分类,纵向对待

    public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    System.out.println("请输入学生星球:");
    String star = s.nextLine();

    System.out.println("请输入学生分数:");
    String score = s.nextLine();
    int sco = Integer.valueOf(score).intValue();

    switch (star) {

    case "地球":
    if (sco > 90) {
    System.out.println("发1000奖学金");
    } else {
    System.out.println("发800奖学金");
    }
    ;
    break;
    case "月球":
    if (sco > 90) {
    System.out.println("发10斤月饼");
    } else {
    System.out.println("发8斤月饼");
    }
    break;
    case "木星":
    if (sco > 90) {
    System.out.println("发10斤钻石");
    } else {
    System.out.println("发8斤钻石");
    }

    第二个问题,case内定义变量,要在冒号后加{}

    如果想在某个case里定义一个变量:
    switch (formWay)
    {
    case 1 :
    int a=2; //错误。由于case不明确的范围,编译器无法在此处定义一个变量。
    ...
    case 2 :
    ...

    }
    在这种情况下,加上{}可以解决问题。
    switch (formWay)
    {
    case 1 :
    { 
    int a=2; //正确,变量a被明确限定在当前{}范围内。
    ...
     } 
    case 2 :
    ...
    }

    public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.println("请输入学生省份:");
    String province = s.nextLine();

    switch (province) {
    case "河北": {
    int a = 13;
    System.out.println("case内定义变量要加{}" + a);
    }
    ;
    break;
    case "山东":
    {
    char c = 'x';
    System.out.println("case内定义变量要加{}"+ c);
    };break;

    case "湖南":
    {
    short b = 100;
    System.out.println("case内定义变量要加{}"+b);
    };
    break;

    case "广州":
    {
    Date d = new Date();
    System.out.println("case内定义变量要加{}"+d);
    }
    break;

    default :
    {
    Pelpel p = new Pelpel();
    p.setAge(20);
    p.setSex(1);
    System.out.println("case内定义变量要加{} 年龄:"+ p.getAge()+" 性别:"+p.getSex());
    }

  • 相关阅读:
    海云健康:上云为10万家药店带去了什么价值?
    PostgreSQL数据目录深度揭秘
    当设计模式遇上 Hooks
    SpringBoot 优雅停止服务的几种方法
    【2021-08-19】连岳摘抄
    【2021-08-18】该休息,还是要好好休息
    【2021-08-17】心里没底,就给它得找个底
    NFLSOJ 1072
    Solution -「ARC 125F」Tree Degree Subset Sum
    Solution -「ARC 125E」Snack
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5566508.html
Copyright © 2020-2023  润新知