简体   繁体   English

使用scanner将文件中的整数读入数组

[英]Using scanner to read integers from a file into an array

I'm working on a review assignment for school. 我正在为学校做一份复习工作。 The assignment is to write a class that reads from standard input a file containing several integers, which are to be put into an array. 赋值是编写一个类,它从标准输入读取一个包含几个整数的文件,这些整数将被放入一个数组中。 From here, methods need to be written that find the average, median, max, min, and standard deviation. 从这里开始,需要编写方法来找出平均值,中位数,最大值,最小值和标准差。

It reads like so: 它读起来像这样:
45 45
56 56
67 67
78 78
89 etc... 89等...

So, I'm assuming I need to create an array list (since the length is undefined) and use scanner to read each line for an integer, then create the methods that will pick apart what I need. 所以,我假设我需要创建一个数组列表(因为长度未定义)并使用scanner读取每一行的整数,然后创建将挑选我需要的方法。 However, I fail to understand how to properly use FileReader and Scanner in conjunction. 但是,我无法理解如何正确使用FileReader和Scanner。 I'm currently running BlueJ. 我目前正在运行BlueJ。 The text file is located under the project folder, yet the file is never found by the code. 文本文件位于项目文件夹下,但代码永远找不到该文件。

Here is what I have so far. 这是我到目前为止所拥有的。

import java.io.*;
import java.util.*;
import java.math.*;
public class DescriptiveStats
{
    public DescriptiveStats(){}
    public FileReader file = new FileReader("students.txt");

    public static void main(String[] args) throws IOException
    {
        try{
            List<Integer> scores = new ArrayList<Integer>();
            Scanner sc = new Scanner(file);
            while(sc.hasNext())
            {
                scores.add(sc.nextInt());
            }
            sc.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }

确保“students.txt”与您运行的代码位于同一目录中(例如,将.java文件编译到的目录),或者将完整路径放到文件中。(“C:/ folder / students” 。文本”)

System.out.println(new File("students.txt").getAbsolutePath()); will give you the path from where java is trying to load the file. 将为您提供java尝试加载文件的路径。

I suspect its due to ambiguity caused by multiple paths in classpath, the first entry being the one from where it loads. 我怀疑它是由于类路径中的多个路径引起的歧义,第一个条目是它加载的那个。 Setting the file load path as the first entry should solve the problem. 将文件加载路径设置为第一个条目应该可以解决问题。

Use Scanner.hasNextInt() (instead of Scanner.hasNext() ): 使用Scanner.hasNextInt() (而不是Scanner.hasNext() ):

...
while(sc.hasNextInt())
{
    scores.add(sc.nextInt());
}
...

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

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