Java If-else语句

如何从键盘获取不同类型的变量:需要使用Scanner类

具体实践步骤:
1、导包:import java.util.Scanner;
2、Scanner的实例化
3、调用Scanner类的相关方法(next() / nextXxx()),来获取指定类型的变量

注意:需要根据相应的方法,来输入指定类型的值。如果输入的数据类型不匹配时,会报异常:InputMisMatchException
导致程序终止

import java.util.Scanner;

class ScannerTest{
	public static void main(String[] args){
		
		Scanner scan = new Scanner(System.in);
		
		System.out.println("请输入你的姓名:");
		String name = scan.next();
		System.out.println(name);
		
		System.out.println("请输入你的芳龄:");
		int age = scan.nextInt();
		System.out.println(age);
		
		System.out.println("请输入你的体重:");
		double whight = scan.nextDouble();
		System.out.println(whight);
		
		System.out.println("你是否相中我了呢?(true/false)");
		boolean isLove = scan.nextBoolean();
		System.out.println(isLove);
		
		System.out.println("性别:");
		String gender = scan.next();
		char genderChar = gender.charAt(0);//获取索引为0位置上的字符
		System.out.println(genderChar);
		
		
	}
}

分支结构中的If-else(条件判断结构)

一、三种结构

第一种:
if(条件表达式){
}

第二种:二选一
if(条件表达式){
执行语句一
}else{
执行语句二
}

第三种:多选一
if(条件表达式){
执行语句一
}else if{
执行语句二
}else if{
执行语句三
}···
else{
}

class IfTest{
	public static void main(String[] args){
		
		//举例一
		int heartBeats = 78;
		if(heartBeats < 60 || heartBeats > 100){
			System.out.println("需要做进一步检查");
		}
		
		System.out.println("检查结束");
		
		//举例二
		
	}
}
import java.util.Scanner;

class IfTest2{
	public static void main(String[] args){
	
	Scanner scan = new Scanner(System.in);
	
	System.out.println("请输入第一个整数:");
	int n1 = scan.nextInt();
	System.out.println("请输入第二个整数:");
	int n2 = scan.nextInt();
	System.out.println("请输入第三个整数:");
	int n3 = scan.nextInt();
	
	int temp = 0;
	
	if(n3 > n2){
		if(n1 <= n2){
			System.out.println(n1 + "," + n2 + "," +n3);
		}else if(n1 >= n3){
			System.out.println(n2 + "," + n3 + "," +n1);
		}else{
			System.out.println(n2 + "," + n1 + "," +n3);
		}
	}else{
		if(n1 <= n3){
			System.out.println(n1 + "," + n3 + "," +n2);
		}else if(n1 >= n2){
			System.out.println(n3 + "," + n2 + "," +n1);
		}else{
			System.out.println(n3 + "," + n1 + "," +n2);
		}
	}
	
	//如何获得一个随机数:10 - 99
	int value = (int)(Math.random() * 90 + 10);//[0.0,1.0)
	System.out.println(value);
	
	}
}
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页