奇怪的file.nextLine()行为

时间:2013-02-27 02:53:21

标签: java file-io

好的,所以我有这个奇怪的问题,我正在尝试获取一个文件来输入几个类。这是方法,其中大部分已被注释掉。在指定的点,我需要放入一个多字符串。但是,当.next()工作时,.nextLine()失败。

java的新手,很抱歉,如果这很明显。

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... ");
   }
}

文件(忽略额外输入,因为它们仅用于格式化。这只是团队的2次迭代。):

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

1 个答案:

答案 0 :(得分:1)

由于Scanner#nextInt不使用换行符,因此紧接1001之后的换行符将传递到nextLine语句,并且您的团队名称将显示为空。

在阅读下一行之前,您需要使用此字符。您可以使用:

fileReader.nextLine(); // consume newline
team.setTeamName(fileReader.nextLine());
相关问题