Java练习_第四天

1.switch后面使用的表达式可以是哪些数据类型的。

在这里插入图片描述

2. 使用switch语句改写下列if语句:

 	 int a = 3;
 	 int x = 100;
 	 if(a==1)
		x+=5;
 	 else if(a==2)
		x+=10;
 	 else if(a==3)
		x+=16;
 	 else		
		x+=34;

    public static void main(String[] args) {
        int a = 3;
        int x = 100;
        switch (a){
            case 1:
                x += 5 ;
                break;
            case 2:
                x += 10;
                break;
            case 3:
                x += 16;
                break;
            default:
                x += 34;
        }

        System.out.println(x);
    }

3、 谈谈你对三元运算符、if-else和switch-case结构使用场景的理解

  • 三元运算符一般我用在二选一,直接返回的return判断中
  • if-else用在条件判断比较少
  • switch用在分支条件较多的情况下。

如果判断的具体数值不多,而且符合byte、short 、char、int、String、枚举等几
种类型。虽然两个语句都可以使用,建议使用swtich语句。因为效率稍高。

其他情况:对区间判断,对结果为boolean类型判断,使用if,if的使用范围更广。
也就是说,使用switch-case的,都可以改写为if-else。反之不成立。

4. 如何从控制台获取String和int型的变量,并输出?使用代码实现


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);


        System.out.println("输入Int:");
        int a = scanner.nextInt();
        System.out.println(a);


        System.out.println("输入字符串:");
        String s = scanner.next();
        System.out.println(s);
    }

5. 使用for循环遍历100以内的奇数,并计算所有的奇数的和并输出。

    public static void main(String[] args) {
        int sum = 0;
        
        for (int i = 1; i < 100; i += 2){
            sum += i;
        }

        System.out.println(sum);
    }

发布了255 篇原创文章 · 获赞 71 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/zhizhengguan/article/details/104155659