首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要从infile中获取每个整数并将其传递给一个方法

需要从infile中获取每个整数并将其传递给一个方法
EN

Stack Overflow用户
提问于 2012-04-15 09:54:42
回答 2查看 469关注 0票数 0

我正在尝试从infile中读取每个整数,并将其传递给adScore方法,该方法确定字母等级、所有等级的总数以及最高考试成绩和最低考试成绩。但是我的while循环在执行for循环时并没有从infile中拉入数据,因为我是在for循环执行system.out.print之后对其进行调试的。返回的只是数字0-29,这是我在循环中的计数器。可以帮助我做错了什么吗?这样我就可以从孩子中拉出分数了吗?

致以问候。

代码语言:javascript
复制
        while(infile.hasNextInt())
        {
            for(int i=0; i <30; i++)//<-- it keeps looping and not pulling the integers from the     file.
            {
                System.out.println(""+i);//<--- I placed this here to test what it     is pulling in and it is just counting
                //the numbers 0-29 and printing them out.  How do I get each data    from the infile to store
                exam.adScore(i);//determines the count of A, B, C, D, F grades, total   count, min and max
            }
        }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-15 13:03:27

Tron是对的-您实际上并没有要求扫描器读取下一个整数。Scanner.hasNextInt()只是简单地测试是否有一个整数需要读取。您只需要告诉i遍历0-29之间的值。我想你的意思是这样做:

代码语言:javascript
复制
while(infile.hasNextInt())
{
    int i = infile.nextInt();
    exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max
}

如果你不确定输入中的每一行都是整数,你可以这样做:

代码语言:javascript
复制
while(infile.hasNext()) { // see if there's data available
    if (infile.hasNextInt()) { // see if the next token is an int
        int i = infile.nextInt(); // if so, get the int
        exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max
    } else {
        infile.next(); // if not an int, read and ignore the next token
    }
}
票数 1
EN

Stack Overflow用户

发布于 2012-04-15 10:04:25

它打印0- 29,因为这是您告诉它要做的事情:

代码语言:javascript
复制
System.out.println(""+i)

将打印出i,它只是您用作循环计数器的整数。实际上,您永远不会从Scanner对象检索下一个值。我猜这是家庭作业,所以我不会给您任何代码,但我会说,您肯定需要使用Scanner的nextInt()方法来从输入文件中检索值,并在for循环中使用该值。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10158951

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档