当前位置: 代码迷 >> 综合 >> java学习笔记——Scanner(键盘输入)
  详细解决方案

java学习笔记——Scanner(键盘输入)

热度:40   发布时间:2024-02-23 09:13:15.0

目录

  • 基本语法
  • next()
  • nextLine()
  • hasNext()和hasNextLine()
    • 与上面的方法(Next()等)一起使用
    • hasNext()和hasNextLine()的区别
    • 注意

基本语法

  • 使用以下基本语法来获取输入
Scanner s = new Scanner(System.in);	//固定语句,实例化输入
  • 通过Scanner类的next()nextLine()方法获取输入字符串,在读取前我们一般使用hasNext() 和**hasNextLine()**来判断是否还有输入的数据。

next()

  • next()只会接受非空白字符
  • 如果接受的字符前面有空格,会自动将空格去掉
  • 如果接收到的字符中间有空格,会将空格后的内容全部去掉
package com.zxw.TEST;import java.util.Scanner;public class Test {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);System.out.println("请输入字符:");String a = scanner.next();System.out.println("您输入的字符为:"+a);}
}

输出:

请输入字符:asdf asd sdfasdf sdf sd f sd
您输入的字符为:asdf

nextLine()

  • nextLine()会将当前输入的全部内容(回车结束)返回
package com.zxw.TEST;import java.util.Scanner;public class Test {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);System.out.println("请输入字符:");String a = scanner.nextLine();System.out.println("您输入的字符为:"+a);}
}

输出

请输入字符:asdf asdf sda fasd f
您输入的字符为:     asdf asdf sda fasd f

hasNext()和hasNextLine()

  • 这两个方法都会返回一个布尔值
  • 当代码中出现这两个方法的时候,程序会发生阻塞,并等待键盘键入数据
  • 键盘键入数据后,该方法返回的布尔值为true
  • hasNextxxx()和Nextxxx()这两个方法最好一一对应。
    例如hasNextLine()对应NextLine(),而hasNext()对应Next()

与上面的方法(Next()等)一起使用

  • 当hasNext()就收到数据后,java会把这些数据存起来。而接下来用Next()这些方法的时候,不会再要求用户键入数据,而是直接从之前储存的数据中读取,当储存的数据全部都被读完时,再使用Next()就会要求用户继续键入数据。
  • 当使用Next()读取储存的数据时,会从上次读到的位置接着往下读取数据
package com.zxw.TEST;import java.util.Scanner;public class Test {
    public static void main(String[] args) {
    //创建一个扫描器对象,用于接受键盘数据boolean a;Scanner scanner = new Scanner(System.in);System.out.println("Input: ");a = scanner.hasNext(); /*程序在此处暂停*/ //程序接收处System.out.println(a);System.out.println("No Input0");//使用next方法接收//判断是否有输入if (scanner.hasNext()/*程序在此处不会暂停*/){
    System.out.println("读取三次,前两次为Next(),最后一次为NextLin()");System.out.println("第一次读取,从头开始读取非空字符,一直读到下一个非空字符");//接收字符串String str = scanner.next(); // 一直读取到空字符System.out.println(str);System.out.println("第二次读取,从上一个位置开始读取非空字符");System.out.println(scanner.next());System.out.println("第三次读取,将剩下的字符全部输出");String str2 = scanner.nextLine();   //将剩下的内容全部读取System.out.println(str2);}scanner.close();//对象用完要关闭,节省资源}
}

输出:

Input: asdfsad sdf sdf sd fa
true
No Input0
读取三次,前两次为Next(),最后一次为NextLin()
第一次读取,从头开始读取非空字符,一直读到下一个非空字符
asdfsad
第二次读取,从上一个位置开始读取非空字符
sdf
第三次读取,将剩下的字符全部输出sdf sd fa

hasNext()和hasNextLine()的区别

  • hasNext():当储存的数据中还有非空字符的时候,返回true。否则会发生阻塞,等待用户键入
  • hasNextLine() :与hasNext()基本一样,只是hasNextLine()是检查输入中是否还有linePattern。其中LinePattern其实是匹配一个正则表达式。
private static final String LINE_SEPARATOR_PATTERN ="\r\n|[\n\r\u2028\u2029\u0085]";
private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$";

注意

只有在从文件中读取数据的时候,hasNextLine() 和hasNext()才会返回false。而从键盘键入时,只有两种情况,true和发生阻塞等待用户键入。

  相关解决方案