【问题标题】:Java Types Basics [duplicate]Java类型基础[重复]
【发布时间】:2015-09-12 11:14:09
【问题描述】:

我试图理解给出的答案,但我不明白为什么答案是“Hello World”,希望有人解释。

public class TestClass{
  public static int getSwitch(String str){
      return (int) Math.round( Double.parseDouble(str.substring(1, str.length()-1)) );
  }
  public static void main(String args []){
    switch(getSwitch(args[0])){
      case 0 : System.out.print("Hello ");
      case 1 : System.out.print("World"); break;
      default : System.out.print("Good Bye");
    }
  }
}

上面的代码用命令行运行会打印什么:java TestClass --0.50(0前有两个减号)

【问题讨论】:

  • getSwitch 函数返回什么?另外,您忘记在case 0: 子句之后加上break;
  • @TheCodingMonk OP 没有编写代码,break 被故意省略,作为一个练习来展示缺少的中断意味着什么。

标签: java


【解决方案1】:

根据JavaDocs Double

parseDouble(String s)

返回一个新的 double,初始化为指定 String 表示的值,由 Double 类的 valueOf 方法执行。

所以改变你的代码:

public static int getSwitch(String str){
return (int) Math.round( Double.parseDouble(str.substring(1, str.length()-1)));
  }

与:

public static long getSwitch(String str){
return Math.round(Double.parseDouble(str));
  }

因为 round(double) 返回 long JavaDocs Math Round

圆形(双a)

返回最接近参数的长整数,并向上取整。

然后将 main 替换为:

  public static void main(String args []){
      switch(getSwitch(args[0])){
      case 0 : System.out.print("Hello");
      break;
      case 1 : System.out.print("World"); 
      break;
      default : System.out.print("Good Bye");
      break;
    }
  }

如果您使用0 运行课程,它会打印Hello 并使用1 打印World,默认操作会根据JavaDocs Switch Satement 打印Good Bye

默认部分处理所有未明确处理的值 由案例部分之一。

【讨论】:

    【解决方案2】:
    public static int getSwitch(String str) {        // str = "--0.50"
        String x = str.substring(1, str.length()-1); // x = "-0.5"
        double y = Double.parseDouble(x);            // y = -0.5
        long z = Math.round(y);                      // z = 0   (ties rounding to positive infinity)
        return (int) z;                              // returns 0
    }
    public static void main(String[] args) {
        switch (getSwitch("--0.50")) {
            case 0:  System.out.print("Hello ");       // executed because getSwitch returned 0
            case 1:  System.out.print("World"); break; // executed because case 0 didn't end with a break
            default: System.out.print("Good Bye");     // not executed because case 1 did end with a break
        }
    }
    

    【讨论】:

      【解决方案3】:

      您的代码已经将答案作为注释。

      上面的代码用命令行运行会打印什么:java TestClass --0.50(0前有两个减号)

      这意味着如果您通过命令行运行代码并传递上述参数,它将存储在位置 0 的String[] args 中,因为它是您唯一的第一个参数。

      之后,您的算法测试字符串并尝试将其转换为double,然后将在您的switch case 中进行测试。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-22
        • 2012-07-06
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        • 2018-01-21
        • 2012-05-28
        • 2017-12-01
        相关资源
        最近更新 更多