数据输入
一、Scanner使用的基本步骤
1、导包
import java.util.Scanner;
(导包的动作必须出现在类定义的上边)
2、创建对象
Scanner sc=new Scanner (System.in)
(只有sc是变量名可以改变,其他的都不能改变)
3、接受数据
int i = sc.nextInt( );
(只有i是变量名可以改变,其他的都不能改变;sc处要和上面一致)
eg:import java.util.Scanner;
public class ScannerDemo{
public static void main(String[] args){
//创建对象
Scanner sc=new Scanner(System.in);
//接收数据
Int x=sc.nextInt();
//输出数据
System.out.println("x"+x);
}
}
二、三个和尚案例
需求:一座寺庙里住着三个和尚,他们的身高必须经过测量得出
请用程序实现获取这三个和尚的最高身高
import java.util.Scanner;
public class ScannerTest{
public static void main(String[] args){
//身高未知,采用键盘录入实现,首先导包,然后创建对象
Scanner sc=new Scanner(System.in);
//键盘录入三个身高分别赋值给三个变量
int height1=sc.nextInt();
int height2=sc.nextInt();
int height3=sc.nextInt();
//用三元运算符获取和尚的较高身高值
int tempHeight=height1>height2?height1:height2;
int maxHeight=tempHeight >height3?tempHeight:height3;
//输出结果
System.out.printfln("maxHeight"+maxHeight);
}
}