StephenJpH
StephenJpH

Reputation: 35

Java Reading from a text file (Strings and integers)

I have this method where i am trying to read in from a text file and then add whats in it to my array ,my method seems to be okay , but when i rum my program i am getting null on the screen please help here is my code.

    File text = new File("C:\\Users\\Stephen\\Desktop\\CA2\\src\\Management_System_Package\\GAMES.txt");
    Scanner scnr = new Scanner(text);

    String GameLine;
    GameLine = scnr.nextLine();

    while (scnr.hasNextLine()) {

        Management_System Game = new Management_System("", "", 0, 0, 0);

        int Comma1 = GameLine.indexOf(", ");
        String Title = GameLine.substring(0, Comma1).trim();
        Game.setTitle(Title);

        System.out.print(Title);

        int Comma2 = GameLine.indexOf(", ", Comma1 + 1 );
        String Genre = GameLine.substring(Comma1 + 1, Comma2);
        Game.setGenre(Genre);

        int Comma3 = GameLine.indexOf(", ", Comma2 + 1 );
        String ID = GameLine.substring(Comma2 + 1, Comma3);
        Game.setID(Double.parseDouble(ID));

        int Comma4 = GameLine.indexOf(", ", Comma3 + 1 );
        String Rating = GameLine.substring(Comma3 + 1, Comma4);
        Game.setRating(Integer.parseInt(Rating));

        String Quantity = GameLine.substring(Comma4 + 1).trim();
        Game.setQuantity(Integer.parseInt(Quantity));

        add(Game);

        GameLine = in.nextLine(); 

Upvotes: 0

Views: 66

Answers (1)

locoyou
locoyou

Reputation: 1697

It is because your code has a bug that you read a line out of the loop and you will always skip the last line of your file. If your file has only one line, scnr.hasNextLine() will be false and the while loop will not be run into.

And I think split() is a better way to get the strings and integers you want. Code like this:

String GameLine;

while (scnr.hasNextLine()) {
    GameLine = scnr.nextLine();
    Management_System Game = new Management_System("", "", 0, 0, 0);
    String[] tags = GameLine.split(",");

    Game.setTitle(tags[0]);

    Game.setGenre(tags[1]);

    Game.setID(Double.parseDouble(tags[2]));

    Game.setRating(Integer.parseInt(tags[3]));

    Game.setQuantity(Integer.parseInt(tags[4]));

    add(Game);
}

Upvotes: 1

Related Questions