Scanner类

Scanner

Scanner: 其中有一个作用是获取键盘上的符号

构造方法:
    Scanner(InputStream source)  构造一个新的 Scanner ,产生从指定输入流扫描的值。
    InputStream 字节流

这里是从键盘输入字符串类型 next() 的和整数类型 nextInt() 的

import java.util.Scanner;

public class ScannerDemo1 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String s1 = sc.next();
        System.out.println("请输入一个整数:");
        int s2 = sc.nextInt();
        
    }
}

当 next() 换成 nextLine() 的时候就不一样了

1.当 next() 在 next() 前面
import java.util.Scanner;

public class ScannerDemo1 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一个字符串:");
//        String s1 = sc.next();
        String s1 = sc.nextLine();
        System.out.println("请输入一个整数:");
        int s2 = sc.nextInt();
        
    }
}
结果为:一样能正常运行

image-20240306210458145

2.当 nextLine() 在 nextInt() 后面
import java.util.Scanner;

public class ScannerDemo1 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一个整数:");
//        String s1 = sc.next();
        int s1 = sc.nextInt();
//        String s1 = sc.nextLine();
        System.out.println("请输入一个字符串:");
//        int s2 = sc.nextInt();
        String s2 = sc.nextLine();

    }
}
结果为:直接在输入完整数之后输出提示句后结束运行了

image-20240306210808560

原因:因为Scanner不是直接接收输入的内容,类比一下,Scanner内部有一个管道,先输入了10,但是在10的后面有个换行符,这个换行符是 nextInt() 前面的println给到的换行符,而 nextLine() 是可以接收换行符的,所以 nextLine() 是把换行符接收到了,不再接收后面的输入值,接着结束了运行,再想输入 nextLine() 的值的时候是不行的

判断输入的数据是否是想要的类型的数据

public boolean hasNextInt() 判断管道中的下一个数据是否是整数
import java.util.Scanner;

public class ScannerDemo1 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int s1=0;
        if (sc.hasNextInt()){
            s1 = sc.nextInt();
        }else{
            Scanner sc1 = new Scanner(System.in);
            System.out.println("请输入一个整数:");
            s1= sc1.nextInt();
        }
//        String s1 = sc.next();
//        String s1 = sc.nextLine();
        System.out.println("请输入一个字符串:");
//        int s2 = sc.nextInt();
        String s2 = sc.next();
        System.out.println("s1"+s1);
        System.out.println("s2"+s2);

    }
}
posted @ 2024-03-06 21:59  peculiar-  阅读(25)  评论(0)    收藏  举报