简体   繁体   中英

How to read a line from a txt file with int and String elements?

I'm trying to create a List by reading a txt file. For example:

12345; Mary Jane ; 20
12365; Annabelle Gibson; NA

Each line contains: number; name; Grade (grade can be a String or a int)

I created the following method;

public static  List <Pauta>leFicheiro( String nomeF) throws       FileNotFoundException{
    List<Pauta> pautaT = new LinkedList<Pauta>();
    try {
    Scanner s = new Scanner(new File (nomeF));
        try{
            List<Pauta> pautaS =pautaT;
            while ( s.hasNextLine()){
                String line = s.nextLine();
                String tokens[]= line.split(";");
                if(s.hasNextInt()) {
                    System.out.println ("next int = " + s.nextInt());
            }
                pautaS.add(new Pauta (s.nextInt(), tokens[1],tokens[2]);
            }
            pautaT = pautaS;
        }
    finally {
        s.close();
    }
    }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (ParseException e){
            e.printStackTrace();
        }       
    return pautaT;
}

Pauta is a class that receives as arguments ( int, String, String), I thought Grade as a String to make it more simple, but if you have ideas on how to still create a List (main goal) by having it String or int I would be thankful.

Now the problem is: The part s.nextInt() is returning error : InputMismatchException

So I put this following code:

catch (InputMismatchException e) {
System.out.print(e.getMessage());}

which says it returns a null.

How can I solve this?

Instead of using the s.nextInt(), parse the first token to an Integer.

See the example below.

public static void main(String... args) throws FileNotFoundException {
        List<Pauta> pautaT = new LinkedList<Pauta>();
        try {
            Scanner s = new Scanner(new File("test.txt"));
            try{
                List<Pauta> pautaS =pautaT;
                while ( s.hasNextLine()){
                    String line = s.nextLine();
                    String tokens[]= line.split(";");
                    pautaS.add(new Pauta (Integer.parseInt(tokens[0]), tokens[1],tokens[2]));
                }
                pautaT = pautaS;
            }
            finally {
                s.close();
            }
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }

    }

This results in the list to be populated.

您可能会使用StringTokenizer,并将同一行的每个标记保存到变量中,然后根据需要使用它们。

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