0

好的,所以我遇到了一个奇怪的问题,我试图获取一个文件来为几个类提供输入。这里是方法,大部分都被注释掉了。在指定点,我需要输入一个多字字符串。但是,虽然 .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
4

1 回答 1

1

因为Scanner#nextInt不消耗换行符,紧随其后的换行符1001将传递给nextLine语句,您的团队名称将显示为空。

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

fileReader.nextLine(); // consume newline
team.setTeamName(fileReader.nextLine());
于 2013-02-27T03:36:33.807 回答