/*
如何从键盘获取不同类型的变量
需要使用Scanner类
具体实现步骤
1,导包: import java.util.Scanner; 可以从API文档查询类名,类的用法
2,Scanner 的实例化:Scanner scan = new Scanner(System.in);
3,调用Scanner类的相关方法,来获取指定类型的变量
注意:需要根据相应的方法来输入指定类型的信息,如果输入的类型与要求的类型不匹配
会报异常 InputMisMatchExcepted并导致程序中止执行,
int型不能写浮点,double型可以写整数,符合自动提升规则可以输入
*/
import java.util.Scanner;
class ScannerTest{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入分数");
int credit = scan.nextInt();
if(credit < 0 || credit > 100){
System.out.println("数据非法");
}else if(credit < 60){
System.out.println("不及格");
}else if(credit < 81){
System.out.println("及格");
}else if(credit < 100){
System.out.println("优秀");
}else if(credit == 100){
System.out.println("满分");
}
System.out.println("请输入姓名");
String name = scan.next(); //获取字符串
System.out.println(name);
System.out.println("请输入年龄");
int age = scan.nextInt(); //获取int整数
System.out.println(age);
System.out.println("请输入体重");
double weight = scan.nextDouble(); //获取浮点数
System.out.println(weight);
System.out.println("是否有医保卡");
boolean haveMedicaSecurity = scan.nextBoolean();//获取布尔类型
System.out.println(haveMedicaSecurity);
//对于char型的数据,Scanner没有提供相关的方法,只能获取字符串
System.out.println("请输入性别:男/女");
String gender = scan.next(); //先获取字符串
char genderChar = gender.charAt(0);//在通过String中的方法获取索引位置为0上的字符,类型为char
System.out.println(genderChar);
}
}
本文详细介绍如何使用Java的Scanner类从键盘获取不同类型变量的输入,包括int、double、String、boolean等,并展示了如何处理输入错误,确保程序的健壮性。
657

被折叠的 条评论
为什么被折叠?



