Scanner类

Scanner类:

API介绍:

在这里插入图片描述
解析:
Scanner类是一个文本扫描器类,对字符串文本进行扫描操作。

构造方法:
在这里插入图片描述在这里插入图片描述在这里插入图片描述

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;

public class Demo4 {
    public static void main(String[] args) throws FileNotFoundException {//throws FileNotFoundException用来抛出io的错误,
        //1,Scanner(File) 扫描文件
        File file = new File("C:\\Users\\Administrator\\Desktop\\text1.txt");
        Scanner input = new Scanner(file);
        //注意:直接输出对象,就是调用该对象的toString()方法
        System.out.println(input);

        //2,Scanner(InputStream) 扫描键盘
        InputStream in = System.in;
        Scanner input2 = new Scanner(in);
        System.out.println(input2);

        //3,Scanner(String) 扫描自定义字符串
        String str = "abc";
        Scanner input3 = new Scanner(str);
        System.out.println(input3);
    }
}

常用功能方法:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

import java.util.Scanner;

public class Demo4 {
    public static void main(String[] args) throws FileNotFoundException {//throws FileNotFoundException用来抛出io的错误,
        Scanner input = new Scanner(System.in);
        String str1 = input.next();
        String str2 = input.nextLine();
        boolean b = input.nextBoolean();
        byte b1 = input.nextByte();
        short s = input.nextShort();
        int i = input.nextInt();
        float f = input.nextFloat();
        double d = input.nextDouble();
        scanner_hasNextInt();
    }
    public static void scanner_hasNextInt(){
        Scanner input = new Scanner(System.in);
        System.out.print("输入一个整数:");
        if (input.hasNextInt()){
            int num = input.nextInt();
            System.out.println(num);
        }else{
            System.out.println("录入有误");
        }
    }
}

注意:(.next() 与 .nextLine()的区别)

  • .next()可以扫描字符串数据,以"",回车,'空字符’作为结束符。
  • .nextLine()可以扫描字符串数据,以回车作为结束符

常见问题:

  • 当使用nextLine获取字符串前,获取数字,该字符串就获取失败,因为nextLine获取了上面回车作为结束符 导致字符串获取失败

解决:

  1. 将nextLine换成next(但如果字符串存在空格,则不行)
  2. 写两次nextLine(第一个nextLine用于获取回车符)
  3. 重新实例化Scanner类
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值