如何在Java中将文本文件中的数据读入数组
我的编程作业有问题。我需要从txt文件中读取数据,并将其存储在并行阵列中。txt文件内容的格式如下:
Line1: Stringwith466numbers
Line2: String with a few words
Line3(int): 4
Line4: Stringwith4643numbers
Line5: String with another few words
Line6(int): 9
注意:“Line1:”、“Line2:”等仅用于显示目的,实际上不在txt文件中
正如你所看到的,它以三的模式进行。txt文件的每个条目是三行、两个字符串和一个int
我想把第一行读入数组,第二行读入另一行,第三行读入int数组。然后将第四行添加到第一个数组中,第五行添加到第二个数组中,第六行添加到第三个数组中
我曾尝试为此编写代码,但无法正常工作:
//Create Parallel Arrays
String[] moduleCodes = new String[3];
String[] moduleNames = new String[3];
int[] numberOfStudents = new int[3];
String fileName = "myfile.txt";
readFileContent(fileName, moduleCodes, moduleNames, numberOfStudents);
private static void readFileContent(String fileName, String[] moduleCodes, String[] moduleNames, int[] numberOfStudents) throws FileNotFoundException {
// Create File Object
File file = new File(fileName);
if (file.exists())
{
Scanner scan = new Scanner(file);
int counter = 0;
while(scan.hasNext())
{
String code = scan.next();
String moduleName = scan.next();
int totalPurchase = scan.nextInt();
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
}
}
上面的代码不能正常工作。当我试图打印出数组的一个元素时。对于字符串数组,它返回null;对于int数组,它返回0,这表明读取其中数据的代码不起作用
任何建议或指导都很受欢迎,因为此时此刻正变得令人沮丧
# 1 楼答案
这将在读取
int
后将扫描仪移动到正确的位置