简体   繁体   中英

Extract content from text file using java

I have a text file that is layed out like this:

57363 Joy Ryder D D C P H H C D
72992 Laura Norder H H H D D H H H
71258 Eileen Over C F C D C C C P
70541 Ben Dover F F F P C C C F
46485 Justin Time F C F C D P D H
61391 Anna Conda D D F D D F D D
88985 Bob Down P F P F P F P P

and I have the following code that reads this:

Scanner keyboard = new Scanner(System.in);
        System.out.println("Filename: ");
        // C:\\Users\\Vick\\PT\\accountFilesDemo_17259747\\src\\accountFilesDemo_17259747\\Grades.txt
        String filename = keyboard.nextLine();

        File myfile = new File(filename);

        try {
            Scanner inputFile = new Scanner(myfile);
            while(inputFile.hasNext())
            {
                String str = inputFile.nextLine();
                System.out.println(str);
            }
            inputFile.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Now I want to know how I can get the student ID which is the first 5 digits and store them somewhere, and then after the student name the 8 letters which are ie DDCPHHCD how do I put these somewhere to hold a value from 1-8 and then I need to add them up and do some math to get a total, and then how do I write these two the student ID and total to seperate text file?

Hints:

  1. Use Scanner to break up each line into the components.

  2. Create a class to hold the information in each row.

  3. Use arrays if you know beforehand how many elements there will be in the array, and use lists (eg ArrayList ) if you don't.

  4. Once you have populated the data structure, then doing the arithmetic and printing the results is simple programming.

These hints answer most of your questions. But I'm not going to code up your homework for you.

How about this:

String str = "57363 Joy Ryder D D C P H H C D";
String[] items = str.split(" ");

You can use a Scanner to separate the tokens of a single line.

String str = "57363 Joy Ryder D D C P H H C D";

    Scanner tokens = new Scanner(str);

    String studentID = tokens.next();

    String name = tokens.next();

    String surname = tokens.next();

    String letters = "";

    while(tokens.hasNext())
    {
        letters = letters + tokens.next() + " ";
    }

    System.out.println("ID = " + studentID +
                       "\nNAME = " + name +
                       "\nSURNAME = " + surname + 
                       "\nLETTERS = "+ letters);

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