简体   繁体   中英

Getting Objects From A Text File

I have a text file like this;

    7-Georgia
    1-Andrew
    6-John
    8-Luke
    9-Erica
    3-Kim
    2-Jude
    5-Phil
    4-Leo

The first column is id and second is name. How can I get these id's and names? So far I wrote this;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {

    @SuppressWarnings("resource")
    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub
        @SuppressWarnings("unused")

        Scanner fromFile = new Scanner(new File("id_name.txt"));
        fromFile.useDelimiter("-");

        while(fromFile.hasNext()){
            String temp = fromFile.next();
            System.out.println(temp);
        }

        while(fromFile.hasNext()){
            String temp= fromFile.next();
            int[] fileID;
            fileID= new int[9];

            for(int i=0; i<9; i++){
                fileID[i]= Integer.parseInt(temp);
            }

            System.out.println(fileID);
        }
    }
}

But this doesn't get the id's. I'm not sure how to fix this, I'd be grateful if you help me.

You have two while loops in your code. Typically one while loop will go through every item until the condition is no longer true. I think you need to rework this to have a better "flow of control" which might mean using only one while loop (with sections to grab the number and then the name.

I imagine that you are looking for results from the second while loop, but by the time you get to it, the first while loop will have exhausted all of your data.

Finally, printing an array will print out the array reference identifier. If you want to actually print the contents of the array, you need a loop over the elements within the array, and you need to print out each array element explicitly.

As an alternative to the array printing technique above (which you should master), you can also use the Arrays.toString(<insert array here>) method call. However, in many cases it will give you a format that is not desired. That's why you need to know the above technique too.

Also, you have one hidden issue. You (in the second while loop) make the assumption that there are only nine inputs. Pay close attention to what you are writing. Every time you have to reach for a number, consider whether it is a "magic" number. Magic numbers are numbers that are in your code with no explanation or reason why they exist. They are indicators of errors in the code made by assumptions that probably won't last the test of time.

For example, you are using the number 9 because you have seen the input file. The next input file will probably not have nine entries in it, and your program will probably not work right if you gave it an input with eight entries, or an input with ten entries. Perhaps you should rewrite the loop to remove the magic number, by making the logic process while there is still (some) input.

Try this on for size

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            Scanner fromFile = new Scanner(new File("id_name.txt"));
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        }

        String[] arr = new String[9];
        String[] oth = new String[9];
        int i = 0;

        while(fromFile.hasNextLine()) {
            String temp = fromFile.nextLine();
            oth[i] = temp.substring(0,1);
            arr[i] = temp.substring(2);
            i++;
        }

        int[] fileID;
        fileID = new int[9];

        for(int j = 0; j < 9; j++) {
            fileID[j] = Integer.parseInt(oth[j]);
        }
    }
}

this should go through and retrieve the numbers( .substring(0,1) ) and then the names( .substring(2) ), and then converting the numbers to int values.

Try the following:

File file=new File("id_name.txt");
int[] fileID;
fileID= new int[9];
String[] result = file.nextLine().split("-");

for (int x = 0; x < result.length; x++){
if (Character.isDigit(result[x])) { // use the isDigit method to get the ids
System.out.println("this is an id");
fileID[i]= Integer.parseInt(result[x]);
}

Actually my friend, there are several mistakes here.

1) When the first while loop completes, it leaves fromfile.hasNext() as false Hence the second loop never starts.

>> To fix this, You need to put it all in one while loop.

2) fileID is an array. You cannot print it using System.out.println(fileID) .

>> You have to tell what kind of output you want. The code will depend on that. For simply printing all the values, you need to make a for loop that prints each value separartely. You should use fileID.length for the no. of times you need to loop it.

3) Basically, fromfile.next() is not the way to do it.

>> You need to use fromfile.nextLine() .

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