Scanner(Scanner)

Scanner

基本语法

Scanner s = new Scanner(System.in);

通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据。

next()

  • 一定要读取到有效字符后才可以结束输入(hasNext()也是);
  • 对输入有效字符之前遇到的空白,next()方法会自动将其去掉;
  • 读取有效字符后,将空白符作为分隔符,即next()方法不能得到带空格的字符串;
  • 用的不多;

nextLine()

  • 以Enter作为结束符,即返回的是输入回车之前的所有字符;
  • 可以获得空白;
  • 常用;

nextInt(),nextDouble()等一样用法

public class Demo01 {
    public static void main(String[] args) {
        //创建一个扫描器对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方法输入为:");

        //判断用户是否输入字符串
        if (scanner.hasNext()){
            //使用next方法接收
            String str = scanner.next();
            System.out.println("输出为:"+str);
        };

        //属于IO流的用完要关闭,以防占用资源
        scanner.close();
    }
}
————————

Scanner

Basic grammar

Scanner s = new Scanner(System.in);

Get the input string through the next() and nextline() methods of scanner class. Generally, you need to use hasnext() and hasnextline() to judge whether there is still input data before reading.

next()

  • You must read the valid characters before you can end the input (so is hasnext());
  • The next () method will automatically remove the blank space encountered before entering valid characters;
  • After reading the valid characters, use the blank character as the separator, that is, the next () method cannot get the string with spaces;
  • Not much use;

nextLine()

  • Take enter as the ending character, that is, all characters before entering carriage return are returned;
  • Blank can be obtained;
  • Commonly used;

nextInt(),nextDouble()等一样用法

public class Demo01 {
    public static void main(String[] args) {
        //创建一个扫描器对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方法输入为:");

        //判断用户是否输入字符串
        if (scanner.hasNext()){
            //使用next方法接收
            String str = scanner.next();
            System.out.println("输出为:"+str);
        };

        //属于IO流的用完要关闭,以防占用资源
        scanner.close();
    }
}