Java - Scanner

Scanner

Scanner位于java,util包下,它主要用户获取用户的输入,当然输入的来源根据不同的构造方法有所不同。


在这里插入图片描述

下面我们通过官方API文档看一下常用的几个方法:

  • close():关闭创建的Scanner
  • hasNext():如果还有输入返回ture
  • hasNextByte()、hasNextDouble()、hasNextFloat()、hasNextInt()……:判断是否还有对应类型的数据输入
  • next():返回下一次输入的数据
  • NextByte()、NextDouble()、NextFloat()、NextInt()……:获取对应类型的输入
import java.util.Scanner;

public class ScannerTest {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        String name = sc.next();
        System.out.println(name);

        String num = "";
        while (sc.hasNextLine()) {
            if (sc.hasNextInt()) {
                num = sc.next();
                System.out.println(num);
            }else {
                num = sc.next();
                System.out.println(num + " is not allowed!");
                break;
            }
        }
    }
}

next() 与 nextLine() 区别

next():

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

nextLine():

  • 以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
  • 可以获得空白。

如果要输入 int 或 float 类型的数据,在 Scanner 类中也有支持,但是在输入之前最好先使用 hasNextXxx() 方法进行验证,再使用 nextXxx() 来读取:

持,但是在输入之前最好先使用 hasNextXxx() 方法进行验证,再使用 nextXxx() 来读取:

Java Scanner 类

发布了461 篇原创文章 · 获赞 122 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/Forlogen/article/details/105597196