java 使用扫描仪将文件中的整数读入数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7314436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using scanner to read integers from a file into an array
提问by tapedeckghost
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
56
67
78
89
etc...
它读起来像这样:
45
56
67
78
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. However, I fail to understand how to properly use FileReader and Scanner in conjunction. I'm currently running BlueJ. The text file is located under the project folder, yet the file is never found by the code.
所以,我假设我需要创建一个数组列表(因为长度未定义)并使用扫描仪读取整数的每一行,然后创建将挑选出我需要的方法。但是,我不明白如何正确地结合使用 FileReader 和 Scanner。我目前正在运行 BlueJ。文本文件位于项目文件夹下,但代码从未找到该文件。
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();
}
}
回答by user623879
Make sure "students.txt" is located in the same directory as the code you are running(eg whereever your .java files get compiled to), or put the full path to the file..ie("C:/folder/students.txt")
确保“students.txt”与您正在运行的代码位于同一目录中(例如,无论您的 .java 文件被编译到何处),或将文件的完整路径..ie("C:/folder/students 。文本文件”)
回答by Rajeev Sreedharan
System.out.println(new File("students.txt").getAbsolutePath());
will give you the path from where java is trying to load the file.
System.out.println(new File("students.txt").getAbsolutePath());
将为您提供 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.
我怀疑这是由于类路径中的多个路径引起的歧义,第一个条目是它加载的那个条目。将文件加载路径设置为第一个条目应该可以解决问题。
回答by Bohemian
Use Scanner.hasNextInt()(instead of Scanner.hasNext()):
使用Scanner.hasNextInt()(而不是Scanner.hasNext()):
...
while(sc.hasNextInt())
{
scores.add(sc.nextInt());
}
...