JAVA小实例(五)

多分枝结构在java中也较为常用,今天我们会讲到俩个方法去实现它。

第一个就是switch-case方法:

public class Switch {
	public static void main(String[] args){
		System.out.println("请输入:");
		Scanner in = new Scanner(System.in);
		int type = in.nextInt();
		
		switch(type){
		case 1 :
			System.out.println("你好");
			
		case 2 :
			System.out.println("早上好");
			break;
		case 3 :
			System.out.println("晚上好");
			
		case 4 :
			System.out.println("再见");
			break;
		default :
			System.out.println("啊,什么啊?");
		}
	}
}

效果如下图所示:

Tips: 根据表达式的结果,寻找匹配的case,并执行case后面的语句,一直到break为止,或者到switch结束为止。

第二个就是if-else方法:

package test;

import java.util.Scanner;

public class IfDuo {
	public static void main(String[] args){
		System.out.println("请输入");
		Scanner in = new Scanner(System.in);
		int type = in.nextInt();
		if(type==1){
			System.out.println("你好");
		}else if(type==2){
			System.out.println("早上好");
		}else if(type==3){
			System.out.println("晚上好");
		}else if(type==4){
			System.out.println("再见");
		}else{
			System.out.println("啊,真的吗?");
			}
	}

}

 效果如下图所示:

 

猜你喜欢

转载自blog.csdn.net/m0_52873333/article/details/121111255