day04-分支结构

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

byte、short、char、int、枚举类型变量、字符串类型。

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;
int a = 3;
int x = 100;

switch(){
    case 1:
        x += 5;
        break;
    case 2:
        x += 10;
        break;        
     case 3:
        x += 16;
        break;
    default:
        x += 34;
        break;        
}

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

(1)三元运算符、swithc-case结构都可以改写成if-else结构,反之,则不成立。

(2)如果三种结构都适合用,且判断的具体数值不多,优先考虑三元运算符或者 switch-case结构,代码简洁、效率略高。

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

(1)导包

import java.util.Scanner;

(2)创建对象

Scanner scanner = new Scanner(System.in);

(3)获取键盘输入的值

String str = scanner.next();
int number = scanner.next
import java.util.Scanner;

public class Demo(){
	public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        int number = scanner.nextInt();
        System.out.println("str: " + str);
        System.out.println("number: " + number)
	}
}

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

public class Demo(){
    public static void main(String args[]){
        int sum = 0;
        for(int i = 1; i <= 100; i++){
            if(i % 2 != 0){
                sum += i;
                System.out.println("i: " + i);
            }
        }
        System.out.println("奇数的和: " + sum);
    }
}
posted @ 2022-11-18 17:08  huxingxin  阅读(20)  评论(0编辑  收藏  举报