为什么不打印任何整数? [英] Why won't this print any integers?

查看:218
本文介绍了为什么不打印任何整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

try {

    Scanner sc = new Scanner(new File("testing.txt"));

    while (sc.hasNextInt()){
        int i = sc.nextInt();
        //timing.add(i);
        System.out.println(i);
    }   

    sc.close();

}catch (FileNotFoundException e) {
    e.printStackTrace();
}

文本文件中包含int和字符串。我可以从文本文件中打印文字,但不能打印数字。

The text file does have int and strings in it. I can get it to print words from the text file, but not the numbers.

文本文件包括以下内容:

The text file includes the following:


Michael 3000
7000 Bilbo
我喜欢2000号吗?
不,
我喜欢9000

Michael 3000
7000 Bilbo
I like the number 2000 do you?
No, I like 9000


推荐答案

你的第一个值(Michael)不是整数,因此它永远不会进入循环体内。

Your first value ("Michael") isn't an integer, therefore it never gets inside of the body of the loop.

也许您想要将代码更改为循环,直到它到达文件末尾,读取和打印整数,但消耗(不打印)非整数值。这样的事情:

Perhaps you want to change the code to loop until it reaches the end of the file, reading and printing integers, but consuming (without printing) non-integer values. So something like this:

import java.util.*;
import java.io.*;

public class Test {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(new File("test.txt"));

        while (sc.hasNext()) {
            if (sc.hasNextInt()) {
                System.out.println(sc.nextInt());
            } else {
                // Just consume the next token
                sc.next();
            }
        }           
        sc.close();
    }
}

这篇关于为什么不打印任何整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆