Java类型基础
我试图理解给出的答案,但我不明白为什么答案是“你好,世界”,希望有人能解释Java类型基础,java,Java,我试图理解给出的答案,但我不明白为什么答案是“你好,世界”,希望有人能解释 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(
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");
}
}
}
如果使用命令行运行,上面的代码将打印什么:
JavaTestClass--0.50
(0之前有两个负号)。您的代码已经有了答案作为注释
如果使用命令行运行,上面的代码将打印什么:JavaTestClass--0.50
(0之前有两个减号)
这意味着,如果您通过命令行运行代码并传递所述参数,那么它将存储在位置0处的String[]args
中,因为这是您唯一的也是第一个参数
之后,您的算法测试字符串并尝试将其转换为double
,然后将根据
parseDouble(字符串s)
返回一个新的double,初始化为指定字符串表示的值,由类double的valueOf方法执行
因此,请更改您的代码:
public static int getSwitch(String str){
return (int) Math.round( Double.parseDouble(str.substring(1, str.length()-1)));
}
与:
因为圆(双)回长
圆形(双a)
返回与参数最接近的long,并向上取整
然后将主管道更换为:
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
printWorld
,默认操作将根据
默认部分处理所有未显式处理的值
通过案例部分之一
getSwitch
函数返回什么?还有,你忘了把中断代码>在案例0:
子句之后。@codingmonk OP没有编写代码,中断
被故意忽略,作为一个练习,以显示缺少中断意味着什么。
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;
}
}
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
}
}