从文本文件中读取数据并求和 [英] Read Data From Text File And Sum Numbers

查看:58
本文介绍了从文本文件中读取数据并求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个充满整数的文本文件中读取数据,并让程序在对它们求和的同时将这些整数打印到屏幕上.这应该不难,但我想不通!!!

I want to read in data from a text file which is full of integers and have the program print those integers out to the screen while summing them. This shouldn't be hard, but I can't figure it out!!!

这是极其简化的文本文件:

Here is the extremely simplified text file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

这是我应该可以工作的代码:

And here is my code that is supposed to work:

import java.util.*;
import java.io.File;
import java.io.IOException;

public class ReadFile
{
    public static void main(String[] args)
    throws IOException
    {
        Scanner textfile = new Scanner(new File("Some_Numbers.txt"));

        filereader(textfile);
    }   


    static void filereader(Scanner textfile)
    {
        int i = 0;
        int sum = 0;

        while(i <= 19)
        {
            System.out.println(textfile.nextInt());
            sum = sum + textfile.nextInt();
            i++;
        }
    }



}

最后,这是我得到的输出:

Finally, here is the output I get:

1
3
5
7
9
11
13
15
17
19
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:838)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at ReadFile.filereader(ReadFile.java:23)
    at ReadFile.main(ReadFile.java:12)

推荐答案

您在循环中调用了 textfile.nextInt() 两次.试试:

You are calling textfile.nextInt() twice in the loop. Try:

static void filereader(Scanner textfile)     
{         
    int i = 0;         
    int sum = 0;          
    while(i <= 19)         
    {       
        int nextInt = textfile.nextInt();          

        System.out.println(nextInt);             
        sum = sum + nextInt;
        i++;         
    }     
}

这篇关于从文本文件中读取数据并求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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