简体   繁体   中英

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.

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.

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:

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.

Any help will be greatly appreciated

You can use your snippet and extend it to read the second .txt file aswell.

Your while loop now has to loop over 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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