JAVA中的Scanner类(IO)[JAVA][译]

Scanner类在java.util包中,有兴趣可以去看看源码.Scanner用来进行基本类型的输入,像int、double、字符串等.Scanner使用简单,但是运行不够高效.

  • 通过预定义标准输入流System.in来创建Scanner类的对象。如果需要读取文件则预定义File类对象.
  • 对于数据类型为XXX的数值的输入,可以使用方法nextXXX().例如,读取一个short类型的数据,可以用nextShort(),注意大小写(驼峰命名法).
  • 读取字符串,用nextLine().
  • 读取单独的字符,可以使用next().charAt(0).方法next()返回的是字符串,而charAt(0)返回的是那个字符串中的第一个字符。

// 用Scanner类来读取各种变量的java代码段
import java.util.Scanner;
public class ScannerDemo1
{
    public static void main(String[] args)
    {
        // 声明对象并且预定义标准输入流进行初始化
        Scanner sc = new Scanner(System.in);

        // 字符串输入
        String name = sc.nextLine();

        // 字符输入
        char gender = sc.next().charAt(0);

        // 数值输入,byte, short and float ,用相似的命名方法
        int age = sc.nextInt();
        long mobileNo = sc.nextLong();
        double cgpa = sc.nextDouble();

        // 打印值,检查输入数据是否正确.
        System.out.println("Name: "+name);
        System.out.println("Gender: "+gender);
        System.out.println("Age: "+age);
        System.out.println("Mobile Number: "+mobileNo);
        System.out.println("CGPA: "+cgpa);
    }
}

Input:

Tom
F
21
1779876543210
3.6

Output:

Name: Tom
Gender: F
Age: 12
Mobile Number: 17798765432210
CGPA: 3.6

有时候我们需要判断输入类型或者是否输入完毕.这时候可以用hasNextXXX()类型的方法来判断是否有XXX类型的数据.如果有,该方法会返回true,否则返回false.例如下面的代码段使用了hasNextInt().对于字符串可以用hasNextLine(),对于单独的字符串可以用hasNext().charAt(0).

// 使用Scanner类读取数据的java代码段
import java.util.Scanner;

public class ScannerDemo2
{
    public static void main(String[] args)
    {
        // 声明对象并初始化
        Scanner sc = new Scanner(System.in);

        // 定义并初始化sum,count
        int sum = 0, count = 0;

        // 判断是否是int类型数据
        while (sc.hasNextInt())
        {
            //输入int类型数据
            int num = sc.nextInt();
            sum += num;
            count++;
        }
        int mean = sum / count;
        System.out.println("Mean: " + mean);
    }
    }

Input:

32
45
56
678

Output:

Mean: 202

Comments

Aman said

为什么Scanner类比较慢?

Sukrit said

慢只是相对的.当Scanner读取的时候,它执行解析操作,把输入内容当作tokens.更好的额方法是使用BufferedReader,它把输入存进缓冲器.非常快.尤其是当你用它读取一整行的时候,更快.怎样读取看情况而 定.

一些补充

java源码一般在JDK安装目录下的src.zip压缩包里.在eclipse可以通过Source Attachment设置进行关联,然后在eclipse中敲代码的时候按住commend单击你想要看的方法久能看到源码了。

Scanner部分源码

next()

 /**
     * Finds and returns the next complete token from this scanner.
     * A complete token is preceded and followed by input that matches
     * the delimiter pattern. This method may block while waiting for input
     * to scan, even if a previous invocation of {@link #hasNext} returned
     * <code>true</code>.
     *
     * @return the next token
     * @throws NoSuchElementException if no more tokens are available
     * @throws IllegalStateException if this scanner is closed
     * @see java.util.Iterator
     */
    public String next() {
        ensureOpen();
        clearCaches();

        while (true) {
            String token = getCompleteTokenInBuffer(null);
            if (token != null) {
                matchValid = true;
                skipped = false;
                return token;
            }
            if (needInput)
                readInput();
            else
                throwFor();
        }
   }

readInput()

   // Tries to read more input. May block.
    private void readInput() {
        if (buf.limit() == buf.capacity())
            makeSpace();

        // Prepare to receive data
        int p = buf.position();
        buf.position(buf.limit());
        buf.limit(buf.capacity());

        int n = 0;
        try {
            n = source.read(buf);
        } catch (IOException ioe) {
            lastException = ioe;
            n = -1;
        }

        if (n == -1) {
            sourceClosed = true;
            needInput = false;
        }

        if (n > 0)
            needInput = false;

        // Restore current position and limit for reading
        buf.limit(buf.position());
        buf.position(p);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值