韩顺平java | Switch01

题目要求:请编写一个程序,该程序可以接收一个字符,比如啊a,b,c,d,e,f,g.

a表示星期一,b表示星期二...

根据用户的输入显示相应的信息,要求使用switch语句完成

package April;
import java.util.Scanner;
public class Switch01 {
    public static void main (String[] args){
        Scanner myScanner = new Scanner(System.in);
        System.out.println("please enter a string");
        char c1 = myScanner.next().charAt(0);//表达式数据类型
        switch(c1){
            case 'a':
                System.out.println("Today is Monday");
                break;
            case 'b':
                System.out.println("Tuesday");
                break; //break does not mean exit of the program, just exit of the switch
            case 'c':
                System.out.println("Wednesday");
                break;
            default:
                System.out.println("Enter a new string");
        }
        System.out.println("process stopped");
    }
}

表达式数据类型应和case后的常量类型一致,

char c = 'a'
switch(c) {
    case 'hello':
        System.out.println{"ok1");

//此时,表达式里的type为char,case里的为String,不等

或者是可以自动转成可以互相比较的类型,比如输入的是字符,而常量是int

char c = 'a'
switch(c) {
    case '20':
        System.out.println{"ok1");

// 此时,表达式里的type为char,case里的为inte,可以转换

switch中表达式的返回值必须是:(byte, short, int, char, enum, String)

case子句中的值必须是常量,而不能是变量

char c = 'a';
char c2 = 'c';
switch(c) {
    case c2:
        System.out.println("ok3");
/此时,c2是变量,是不可以存在于case中的子句中的
char c = 'a';
switch(c) {
    case 'b' + 1:
        System.out.println("ok3");
/这样是可以的,因为‘b' + 1 依旧是常量

default子句是可选的,当没有匹配的case时,执行default

break语句用来在执行一个case分支后使用程序跳出switch语句快;如果没有写break,程序会顺序执行到switch结尾。

char c = 'a';
switch (c) {
    case 'a':
        System.out.println("ok1"); //c=a,输出ok1,没有break,输出ok2。
    case 'b':
        System.out.println("ok2")
        break;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值