Java-将数据从txt文件传输到数组
我目前正在尝试开发一个程序,该程序使用学生ID和GPA(取自一个txt文件),并使用这些来做许多其他事情,比如根据GPA范围将学生分为8个类别中的1个,制作每组学生的直方图,并根据GPA对学生进行排名。然而,我需要做的第一件事是将学生ID和GPA转移到两个单独的数组中 我知道创建数组的语法如下:Java-将数据从txt文件传输到数组,java,arrays,file,java.util.scanner,Java,Arrays,File,Java.util.scanner,我目前正在尝试开发一个程序,该程序使用学生ID和GPA(取自一个txt文件),并使用这些来做许多其他事情,比如根据GPA范围将学生分为8个类别中的1个,制作每组学生的直方图,并根据GPA对学生进行排名。然而,我需要做的第一件事是将学生ID和GPA转移到两个单独的数组中 我知道创建数组的语法如下: elementType[] arrayRefVar = new elementType[arraySize] public static void main(String[] args) throws
elementType[] arrayRefVar = new elementType[arraySize]
public static void main(String[] args) throws Exception // files requires exception handling
{
String snum;
double gpa;
Scanner gpadata = new Scanner(new File("studentdata.txt"));
while (gpadata.hasNext()) // loop until you reach the end of the file
{
snum = gpadata.next(); // reads the student's id number
gpa = gpadata.nextDouble(); // read the student's gpa
System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window
}
}
但是,我仍然不知道如何将从文件读取的数据传递到两个单独的数组中。我必须从txt文件中读取数据的代码如下:
elementType[] arrayRefVar = new elementType[arraySize]
public static void main(String[] args) throws Exception // files requires exception handling
{
String snum;
double gpa;
Scanner gpadata = new Scanner(new File("studentdata.txt"));
while (gpadata.hasNext()) // loop until you reach the end of the file
{
snum = gpadata.next(); // reads the student's id number
gpa = gpadata.nextDouble(); // read the student's gpa
System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window
}
}
所以我的问题是:如何将这些信息传递到两个单独的数组中?很抱歉,如果我的问题很难理解,我对编程非常陌生。我已经在这个项目上被难住了很长一段时间,任何帮助都将不胜感激!谢谢。您可以在while循环之前创建两个数组,然后将循环中的每个元素添加到每个数组中。但这种方法有一个问题:我们不知道值的数量,因此无法为此创建固定大小的数组。我建议改用
ArrayList
,它可以根据需要增长。大概是这样的:
public static void main(String[] args) throws FileNotFoundException {
Scanner gpadata = new Scanner(new File("studentdata.txt"));
List<String> IDs = new ArrayList<>();
List<Double> GPAs = new ArrayList<>();
while (gpadata.hasNext()) // loop until you reach the end of the file
{
String snum = gpadata.next(); // reads the student's id number
double gpa = gpadata.nextDouble(); // read the student's gpa
IDs.add(snum);
GPAs.add(gpa);
System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window
}
// Use IDs and GPAs Lists for other calculations
}
请注意,我们需要一个
计数器
(aka.index)变量来寻址阵列插槽。我应该澄清一下,程序声明您可以假设文件的编号永远不会超过1000个&GPA。根据此信息,我在回答中添加了另一个解决方案。