文章目录
Scanner使用的基本步骤
-
导包
import java.util.Scanner;
导包的动作必须出现在类定义的上边 -
创建对象
Scanner sc = new Scanner(System.in);
上面这个格式里面,只有sc是变量名,可以变,其他的都不允许变。 -
接收数据
int i = sc.nextInt();
上面这个格式里面,只有i是变量名,可以变,其他的都不允许变。
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
sc.nextLine(); // 读取并丢弃换行符
String input = sc.nextLine();
System.out.println("num is "+num);
System.out.println("input is "+input);
}
}
案例
需求:一座寺庙里住着三个和尚,他们的身高必须经过测量得出,请用程序实现获取这三个和尚的最高身高。
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the height of the first monk ");
int height1 = sc.nextInt();
System.out.println("Enter the height of the Second monk ");
int height2 = sc.nextInt();
System.out.println("Enter the height of the third monk ");
int height3 = sc.nextInt();
int height = height1 > height2 ? height1 : height2;
height = height > height3 ? height : height3;
System.out.println("The tallest monk is " + height);
}
}