08、Scanner接收键盘输入

java.util.Scanner 是Java5的新特性,通过Scanner可以获取到用户的键盘输入。

创建 java.util.Scanner 对象:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
}

hasNexthasNextLine 区别:

  • 相同点:判断键盘是否还有输入的数据。

不同点: hasNext

  • 一定要读取到有效字符后才可以结束输入
  • 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉
  • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符
  • next() 不能得到带有空格的字符串
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // 判断是否接收数据
    if (scanner.hasNext()) {
        // 接收一个int类型数据
        int age = scanner.nextInt();
        System.out.println("输入的年龄为:" + age);
    } 

    scanner.close();	// 关闭流
}

hasNextLine

  • 以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
  • 可以获得空白。
public static void main(String[] args) {
    Scanner scanner = new Scanner();
    
    // 判断是否接收数据
    if (scanner.hasNextInt()) {
        int age = scanner.nextInt();
        System.out.println("输入年龄为:" + age);
    }
    
    scanner.clone();
}

获取其他类型数据,建议在读取之前先使用 hasNextXxx() 方法验证,再使用 nextXxx() 读取

public static void mian(String[] args) {
	Scanner scanner = new Scanner(System.in);
    // 获取 byte 类型数据
    byte b = scanner.nextByte();
    
    // 获取 short 类型数据
    short b = scanner.nextShort();
    
    // 获取 char 类型数据
    char b = scanner.nextChar();
    
    // 获取 int 类型数据
    int age = scanner.nextInt();
    
    // 获取 long 类型数据
    long b = scanner.nextLong();
    
    // 获取 float 类型数据
    float num = scanner.nextFlot();
    
    // 获取 double 类型数据
    double b = scanner.nextDouble();
    
    // 获取 boolean 类型数据
    boolean b = scanner.nextBoolean();
    
    // 获取 String 类型数据
    String str = scanner.nextLine();
}

原创博主:Little Tomcat
博主原文链接:https://mp.weixin.qq.com/s/-g_F1Qxj2P6gxRchV_6mVw

posted @ 2021-08-15 23:36  LittleTomato  阅读(185)  评论(0)    收藏  举报