秦疆的Java课程笔记:33 流程控制 Scanner

发布时间 2023-11-20 15:06:49作者: Acolyte_9527
  • 之前学习的基本语法中并没有实现程序和人的交互,但是Java给我们提供了这样一个工具类,可以获取用户的输入。
  • java.util.Scanner是Java5的新特性,可以通过Scanner类来获取用户的输入。
  • 基本语法:Scanner s = new Scanner(System.in);
  • 通过Scanner类的nexr()nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()hasNextLine()判断是否还有输入的数据。
package acolyte.scanner;  
import java.util.Scanner;  
public class Demo1 {  
    public static void main(String[] args) {  
  
        //创建一个扫描器对象,用来接收键盘的数据  
        Scanner s = new Scanner(System.in);  
        System.out.println("使用next方式接收:");
  
        //判断用户有没有字符串输入  
        if (s.hasNext()){   //使用next方式接收  
            String str = s.next();  
            System.out.println("输入的内容为:"+str);  
        }  
  
        s.close();//凡是属于I/O流的类,如果不关闭会一直占用资源,要养成好习惯用完就关  
    }  
}
=========
输出效果是:
使用next方式接收:   //这时程序会在一步等待用户输入
hello world         //假如输入这串字符(回车确认)
输出内容为:hello    //只会输出hello,程序结束

hasNextLine()重写上述代码:

package acolyte.scanner;  
import java.util.Scanner;  
public class Demo2 {  
    public static void main(String[] args) {  
        Scanner s = new Scanner(System.in);  
        System.out.println("使用NextLine方式输出:");  
        if(s.hasNextLine()) {  
            String str = s.nextLine();  
            System.out.println("输入内容为:"+str);  
            s.close();  
        }  
    }  
}
=========
输出效果是:
使用nextLine方式接收:   
hello world         
输出内容为:hello world   //这下完整输出hello world,程序结束
  • next()方法

    • 一定要读取到有效字符后才可以结束输入。
    • 对输入有效字符之前遇到的空白,next()方法会自动将其去掉。
    • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
    • next()不能得到带有空格的字符串。
  • nextLine()方法

    • 以Enter(回车)为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符。
    • 可以获得空白。
  • 上面的if语句是为了之后的学习预演的,实际上不用也完全没问题:

package acolyte.scanner;  
import java.util.Scanner;  
public class Demo3 {  
    public static void main(String[] args) {  
        Scanner s = new Scanner(System.in);  
        System.out.println("请输入数据:");  
        String str = s.nextLine();  
        System.out.println("输入内容为:" + str);  
        s.close();  
    }  
}
=========
输出效果是:
请输入数据:   
床前明月光 疑是地上霜         
输出内容为:床前明月光 疑是地上霜