简体   繁体   English

从文本文件中读取数据并求和

[英]Read Data From Text File And Sum Numbers

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)

You never increment i , so the while loop continues beyond the end of the file.您永远不会增加i ,因此 while 循环会继续超出文件末尾。 As for summing, do something like this.至于总结,做这样的事情。

static void addstuff(Scanner aScanner) {
        int sum = 0;

        while (aScanner.hasNextInt()) {
            sum += aScanner.nextInt();
        }

        System.out.println(sum);
}

This will run until hasNextInt() returns false, which occurs when the next item the scanner sees isn't an integer.这将一直运行,直到hasNextInt()返回 false,当扫描器看到的下一个项目不是整数时,就会发生这种情况。 This could be non-numeric input or the end of the file.这可能是非数字输入或文件结尾。 This means you're no longer limited to 25 integers - it'll read as many as it can before stopping.这意味着您不再限于 25 个整数 - 它会在停止之前尽可能多地读取。

Because you never increment i , it never changes from 0, so it is always less than 25. That means it tries to look again after it has done 25 elements, but there is no 26th, so there's an exception.因为你永远不会增加i ,它永远不会从 0 改变,所以它总是小于 25。这意味着它在完成 25 个元素后尝试再次查看,但没有第 26 个,所以有一个例外。

Instead of a while loop, I would recommend a for loop.我建议使用for循环while不是while循环。

To sum them, instead of printing them out, just add to an accumulator.总而言之,与其将它们打印出来,不如将它们添加到累加器中。

int accumulator = 0;
for(int i = 0; i < 25; i++)
    accumulator += aScanner.nextInt();

System.out.println(accumulator);

should print out the sum.应该打印出总和。

You are calling textfile.nextInt() twice in the loop.您在循环中两次调用 textfile.nextInt() 。 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++;         
    }     
}

In addition to lockstock's answer, you might want to consider adding textfile.hasNext() OR textfile.hasNextInt() for your while loop.除了 lockstock 的答案之外,您可能还需要考虑为 while 循环添加 textfile.hasNext() 或 textfile.hasNextInt() 。

static void filereader(Scanner textfile) {
int sum = 0;          
while(textfile.hasNextInt()) {
    int nextInt = textfile.nextInt();
    System.out.println(nextInt);
    sum += nextInt;
}

} }

You will have to do following thing你将不得不做以下事情

    while(i < 25)
    {
        System.out.println(aScanner.nextInt());
        i++ ;
    }

It throws an exception because you don't increment i in the loop.它引发异常,因为您没有在循环中增加i In case if the number of integers in the input file is unknown, you can use the Scanner.hasNextInt() method to check the presence of the next integer (or just use hasNext() to check for EOF).如果输入文件中的整数数量未知,您可以使用Scanner.hasNextInt()方法检查下一个整数是否存在(或仅使用hasNext()检查 EOF)。

You can sum the numbers like in the code snippet below:您可以对下面的代码片段中的数字求和:

    ...
    int sum = 0;
    while(i++ < 25)
    {
        sum += aScanner.nextInt();
    }

or要么

    ...
    int sum = 0;
    while(aScanner.hasNextInt())
    {
        sum += aScanner.nextInt();
    }

You are getting the error (exception) because your file has very big numbers that do not fit on Integer types.您收到错误(异常)是因为您的文件中有非常大的数字,不适合Integer类型。 You should use Long .你应该使用Long

So, use: aScanner.nextLong() instead of aScanner.nextInt() .所以,使用: aScanner.nextLong()而不是aScanner.nextInt()

EDIT: You should also change the type of the sum variable from int to long .编辑:您还应该将sum变量的类型从int更改为long

Your code will work fine.您的代码将正常工作。

1. Your i is never Incremented. 1.你的i永远不会增加。

2. You are not adding up numbers. 2.不是在把数字加起来。

3. addstuff(diskScanner) is a static memeber , so call it with class name with dot operator. 3. addstuff(diskScanner)是一个static memeber ,所以用类名和点运算符调用它

Eg:例如:

Add.addstuff(diskScanner);

   static void addstuff(Scanner aScanner)
{
    int i = 0;
    long l = 0;


    while(i < 25)
    {
        l = i + l;
        i++;
    }

    System.out.println(l);



}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM