Scanner使用的基本步骤
- 导包。Scanner类在java.util包下,所以需要将该类导入。导包的语句需要定义在类的上面。
import java.util.Scanner;
2.创建Scanner对象。
Scnner sc = new Scanner(System.in);//创建Scanner对象,sc表示变量名,其他均不可变```
3.接收数据
```java
int i = sc.nextInt();
示例
import java.util.Scanner;
public class ScannerDemo {
//创建对象
Scanner sc = new Scanner(System.in);
//接收数据
int x = sc.nextInt();
//输出数据
System.out.println(x);
}
改写三个和尚案例
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args){
System.out.println("请输入第一个和尚的身高");
Scanner sc = new Scanner(System.in);
int height1 = sc.nextInt();
System.out.println("请输入第二个和尚的身高");
int height2 = sc.nextInt();
System.out.println("请输入第三个和尚的身高");
int height3 = sc.nextInt();
int tempHeight = height1 > height2 ? height1:height2;
int maxHeight = tempHeight > height3 ? tempHeight:height3;
System.out.println("maxHeight="+maxHeight+"cm");
}
}