简体   繁体   English

如何从文本文件读取,从整数拆分字符串,然后将整数传递到arraylist?

[英]How to read from text file, split strings from integers and then pass integers into an arraylist?

so I am very new to programming and have been trying out some exercises to better learn java. 因此,我对编程非常陌生,并一直在尝试一些练习以更好地学习Java。

Right now, I have a program that reads exam marks from a text file(contains only integers exclusively) and then passes that onto the arraylist. 现在,我有一个程序可以从文本文件(仅包含整数)读取检查标记,然后将其传递到arraylist上。

Something like: 就像是:

exammarks.txt file contains:
23 45 67 76 12


Scanner fileScan = new Scanner(new File("exammarks.txt");
ArrayList<Integer> marksArray = new ArrayList<Integer>();
while (fileScan.hasNextInt())
{
    marksArray.add(fileScan.nextInt());
}

Print out: [23, 45, 67, 76, 12]

However I would like to modify this so that the exammarks.txt file contains: 但是,我想对此进行修改,以便exammarks.txt文件包含:

name grade
NAME 56
NAME2 67
NAME3 43

and that the program reads this text file, ignores the first line, then splits the strings from the integers and then adds the integers onto the ArrayList. 并且程序读取此文本文件,忽略第一行,然后从整数中拆分字符串,然后将整数添加到ArrayList上。

Any help will be greatly appreciated 任何帮助将不胜感激

You can use your snippet and extend it to read the second .txt file aswell. 您可以使用代码片段并将其扩展为读取第二个.txt文件。

Your while loop now has to loop over lines . 现在,您的while循环必须遍历lines

fileScan.nextLine(); // skip first line
    while (fileScan.hasNextLine())
    {
        marksArray.add(Integer.valueOf(fileScan.nextLine().split(" ")[1]));
    }

So what happens here is that first you get the nextLine , split it by " " and get the second part where the Integer sits. 因此,这里发生的事情是,首先获得nextLine ,将其除以" "然后获得第二个Integer所在的位置。 But since nextLine returns a String which is split in two Strings you have to cast it to Integer or use the static method Integer.valueOf . 但是由于nextLine返回一个分为两个字符串的String,所以您必须将其nextLineInteger或使用静态方法Integer.valueOf

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

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