Scanner sc = new Scanner(System.in);// 创建Scanner对象,sc表示变量名,其他均不可变
3、接收数据
int i = sc.nextInt(); // 表示将键盘录入的值作为int数返回。
示例: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);
}
}
这边还可以玩个猜数字的游戏
mport java.util.Random;
import java.util.Scanner;
public class NumberRiddle {
public static void main(String[] args) {
Random r = new Random();
int number = r.nextInt(100) + 1;
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("输入一个猜的数字");
int guessNumber = sc.nextInt();
if (guessNumber > number) {
System.out.println("你猜的数字大了");
} else if (guessNumber < number) {
System.out.println("你猜的数字小了");
} else {
System.out.println("恭喜你猜中了");
break;
}
}
}
}