Xenorosth
Xenorosth

Reputation: 132

Weird file.nextLine() behavior

Okay, so I'm having this weird issue where I'm trying to get a File to give input into several classes. Here is the method, most of which is commented out. At the specified point, I'm needed a multi-word string put in. However, while .next() works, .nextLine() fails.

New to java, so sorry if this is obvious.

public void readWeeklyData (String fileName) 
{
  try{
        File file = new File(fileName);
        Scanner fileReader = new Scanner(file);

        _leagueName = fileReader.nextLine(); //Outputs String properly despite spaces
        _leagueID = fileReader.nextInt();
        _numTeams = fileReader.nextInt();
       _numWeek = fileReader.nextInt();

      int i = 0;
      int j = 0;

       // while(i < _numTeams)
       // {
            Team team = new Team();
            team.setTeamID(fileReader.nextInt());
            System.out.println(team.getTeamID()); //Outputs 1011 properly
            team.setTeamName(fileReader.nextLine()); //Outputs nothing, with or without the while loops in comments. Yet when changed to fileReader.next(), it gives the first word of the team name.
           // team.setGamesWon(fileReader.nextInt());
          //  team.setGamesLost(fileReader.nextInt());
          //  team.setRank(fileReader.nextInt());

          // while(j < 3)
          //  {
           //     Bowler bowler = new Bowler();
         //       bowler.setBowlerId(fileReader.nextInt());
           //     bowler.setFirstName(fileReader.nextLine());
           //     bowler.setLastName(fileReader.nextLine());
          //      bowler.setTotalGames(fileReader.nextInt());
           //     bowler.setTotalPins(fileReader.nextInt());

           //     team.setBowler(j, bowler);
           //     j++;
           // }   

           // j = 0;

          //  _teams[i] = team; 
          //  i++;
        //}

   }

   catch(IOException ex)
    {
        System.out.println("File not found... ");
   }
}

The file (Ignore the extra enters, as they were only there for formatting. This is only 2 iterations of teams.):

Friday Night Strikers
27408
4
0
1001
Fantastic Four
0
0
0
10011
Johnny
Blake
0
0
10012
Donald
Duck
0
0
10013
Olive
Oil
0
0
10014
Daffy
Duck
0
0
1002
The Showboats
0
0
0
10021
Walter 
Brown
0
0
10022
Ty
Ellison
0
0
10023
Gregory
Larson
0
0
10024
Sharon
Neely
0
0

Upvotes: 0

Views: 478

Answers (1)

Reimeus
Reimeus

Reputation: 159874

Because Scanner#nextInt doesn't consume newline characters, the newline character immediately after 1001 will be passed though to the nextLine statement and your team name will appear empty.

You need consume this character before reading the next line. You can use:

fileReader.nextLine(); // consume newline
team.setTeamName(fileReader.nextLine());

Upvotes: 1

Related Questions