Scanner类是一个可以帮助用户键盘输入内容的一个类。
一.基本的Scanner输入
①输入整数、小数
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int a = scanner.nextInt();double b = scanner.nextDouble();System.out.println(a);System.out.println(b);}}
运行截图
②输入一维数组
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();//定义数组长度为nint[] arr = new int[n];//定义一个长度为n,名叫arr的数组for (int i = 0; i < n; i++) {arr[i]=scanner.nextInt();}System.out.print("Scanner输入的数组为:");for (int i = 0 ; i < n ; i++) {System.out.print(arr[i]+" ");}}}
运行截图
输入二维数组
import java.util.Scanner;public class Test2 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();int m = scanner.nextInt();int[][] mat = new int[n][m];System.out.println("请输入整数型的二维数组:");for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {mat[i][j]=scanner.nextInt();}}for (int i = 0; i < n; i++) {System.out.print("[");for (int j = 0; j < m; j++) {if(j==m-1) {System.out.print(mat[i][j]);}else {System.out.print(mat[i][j]+",");}}System.out.print("]");System.out.println();}}}
运行截图
③输入字符串数组
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();String[] arr = new String[n];for(int i = 0 ; i < n ; i ++) {arr[i]=scanner.next();}System.out.println("输入的字符串数组为:");for (int i = 0; i < arr.length; i++) {System.out.print(arr[i]);}}}
运行截图
二.例【猜数字】
创建ScannerDemo类,首先在主方法中创建一个随机数,然后再创建一个while循环不断获取用户输入的数字,让用户输入的数字与随机数比较,给出“大于”或“小于”的提示,直到用户输入的数字与随机数相等才结束循环。
import java.util.Random;import java.util.Scanner;public class ScannerDemo {public static void main(String[] args) {Random r = new Random();int num = r.nextInt(100);int input = -1;Scanner scanner = new Scanner(System.in);while(true) {System.out.println("猜一猜随机数是多少?");input=scanner.nextInt();if (input>num) {System.out.println("你输入的数字大了!");}else if(input<num) {System.out.println("你输入的数字小了!");}else if(input==num) {break;}else {System.out.println("您的输入有误!");}}System.out.println("恭喜你答对了!");scanner.close();}}
运行截图