1

まず第一に、私はこれらすべてに慣れていないので、気楽に言ってください。

と呼ばれるメソッドを作成するタスクが与えられましたが、loadLeague()これはすべての努力にもかかわらず、非常に困難であることが判明しました! 助けていただけないでしょうか。タスク自体は、サッカーのリーグ テーブルに関するものです。私のメソッドは問題なくコンパイルされますが、メイン (またはその他の標準出力) に「InputMismatchException」エラーが出力されます。私は文字通り私の髪を引っ張っています(まあ、残っているものです)、Javaに関するすべての本を一字一句読んだので、何が間違っているのだろうかと思います!! あなたの素敵な専門家は、以下の私のコードを見て、私を正しい方向に向けてくれませんか?

ありがとうございます!

PS このフォーラムに感謝したいと思います。このフォーラムのおかげで、IT 業界での最初の仕事に就くことができました。ここでコメントしたり質問したりすることはめったにありませんが、他の人からのコメントや質問を毎晩読んでいます。これらは面接で本当に役に立ちました。本当にありがとうございました!

import java.io.*;
import java.util.*;

/**  
 * Class League - An instance of this class represents the teams in a
 * football (or similar) league. It provides a class method for creating
 * a new instance of League by reading the data for the teams from a CSV
 * file.
 * 
 * @author Lewis Jones 
 * @version 1.0
 */

public class League
{
   /* instance variables */
   private String name;  // The name of the league
   private Team[] teams; // An array to hold the teams in the league

   /**
    * Constructor for objects of class League. It sets the name of the league
    * to the String object provided as the first argument and initialises teams
    * to an array of the size provided as the second argument. This constructor 
    * is private as it is intended for use only by the class method loadLeague().
    */
   private League(String aName, int size)
   {
      super();
      this.name = aName;
      this.teams = new Team[size];
   }

   /* class method */
   /**
    * This method creates a new League object by reading the required details from
    * a CSV file. The file must be organised as follows:
    *     name(String), number of teams (int)
    *     team name(String), won(int), drawn(int), lost(int), for(int), against    (int)
    *        and so on for each team
    * Having created the new League object the method should create all the Team 
    * objects (using the data in the file to set their attributes) and add them 
    * to the teams array.
    */
   public static League loadLeague()
   {
      League theLeague = null;
      String pathname = OUFileChooser.getFilename();
      File aFile = new File(pathname);
      Scanner bufferedScanner = null;

      try
      {
         String leagueName;
         int numberOfTeams;

         String teamName;
         int won;
         int drawn;
         int lost;
         int goalsFor;
         int goalsAgainst;
         Scanner lineScanner;
         String currentLine;
         bufferedScanner = new Scanner(new BufferedReader(new FileReader (aFile)));    

         while (bufferedScanner.hasNextLine())
         {
            currentLine = bufferedScanner.nextLine();
            lineScanner = new Scanner(currentLine);
            lineScanner.useDelimiter(",");

            leagueName = bufferedScanner.next();
            numberOfTeams = bufferedScanner.nextInt();

            teamName = bufferedScanner.next();
            won = lineScanner.nextInt();
            drawn = lineScanner.nextInt();
            lost = lineScanner.nextInt();
            goalsFor = lineScanner.nextInt();
            goalsAgainst = lineScanner.nextInt();

            Team aTeam = new Team(lineScanner.next());
            aTeam.setWon(lineScanner.nextInt());
            aTeam.setDrawn(lineScanner.nextInt());
            aTeam.setLost(lineScanner.nextInt());
            aTeam.setGoalsFor(lineScanner.nextInt());
            aTeam.setGoalsAgainst(lineScanner.nextInt());
            Team[] teams = new Team[numberOfTeams];
            teams[numberOfTeams] = aTeam;
            numberOfTeams++;
            theLeague = new League(leagueName, numberOfTeams);
         }
      }  
      catch (Exception anException)
      {
         System.out.println("Error: " + anException);
      }
      finally
      {
         try
         {
            bufferedScanner.close();
         }
         catch (Exception anException)
         {
            System.out.println("Error: " + anException);
         }
      }
      return theLeague;
   }

   /* instance methods */

   /**
    * Displays the league table in tabular format to the standard output
    */
   public void display()
   {
      System.out.println(this.name);
      System.out.format("%20s %2s %2s %2s %2s %2s %2s %    2s\n","","P","W","L","D","F","A","Pt");
      for (Team eachTeam : this.teams)
      {
         System.out.format("%20s %2d %2d %2d %2d %2d %2d %2d\n",
                       eachTeam.getName(), eachTeam.getPlayed(), 
                       eachTeam.getWon(), eachTeam.getDrawn(), 
                       eachTeam.getLost(),eachTeam.getGoalsFor(), 
                       eachTeam.getGoalsAgainst(), eachTeam.getPoints());        
      }
   }

   /**
    * Arrange the elements of teams in their natural order. This will only
    * work if a natural order has been defined for the class Team.
    */
   public void sort()
   {
      // to be written later...
   }
}

編集: 以下は、このタスクに付属するサンプル (入力) ファイルです。謝罪いたします。昨夜の投稿にこれを含めるのを完全に忘れていました。

Scottish League Division 1,10
Airdrie United ,3,2,11,14,25
Clyde          ,5,7,4,21,17
Dundee         ,7,2,7,21,18
Gretna         ,10,3,3,43,20
Hamilton Acas  ,7,5,4,19,20
Livingstone    ,6,6,4,21,15
Partick Thistle,8,4,4,25,29
Queen of South ,3,3,10,11,31
Ross County    ,4,4,8,14,24
St Johnstone   ,6,6,4,26,16
4

1 に答える 1

2

私は問題がどこにあるかを正確に知っています。入力ファイルが正しくフォーマットされていません。たとえば、「int」を期待している場合、文字列などの別の形式を読み取っています。私はあなたの入力を持っていないので、ここにその例外がどのように生成されるかを示す簡単な例があります:


サンプルファイルには、次の行が含まれています。

Sample.txt
1,8,6,3
1,2、無効、3

ご覧のとおり、2行目でエラーが発生するため、Sample.txtの1行目のみが印刷されます。 出力:
1、8、6、3

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at staxpro.StAXPro.main(StAXPro.java:35)
public static void main(String[] args) {
        try {
            Scanner bufferedScanner = new Scanner(new BufferedReader(new FileReader ("Sample.txt")));
            while (bufferedScanner.hasNextLine()) {
                String currentLine = bufferedScanner.nextLine();
                Scanner lineScanner = new Scanner(currentLine);
                lineScanner.useDelimiter(",");

                int first = lineScanner.nextInt();
                int second = lineScanner.nextInt();
                // Here is where I read a string than an int value
                // on the 2nd line of the input file
                int third = lineScanner.nextInt();
                int forth = lineScanner.nextInt();


                System.out.println(first + ", " + second + ", " + third + ", " + forth);
            }
        } catch (FileNotFoundException ex) {
            System.err.println(ex.getLocalizedMessage());
        }
    }

編集:

コードと入力ファイルをざっと見てみると、別の問題が見つかりました。

teamName = bufferedScanner.next();
            won = lineScanner.nextInt();
            drawn = lineScanner.nextInt();
            lost = lineScanner.nextInt();
            goalsFor = lineScanner.nextInt();
            goalsAgainst = lineScanner.nextInt();

            Team aTeam = new Team(lineScanner.next());
            aTeam.setWon(lineScanner.nextInt());
            aTeam.setDrawn(lineScanner.nextInt());
            aTeam.setLost(lineScanner.nextInt());
            aTeam.setGoalsFor(lineScanner.nextInt());
            aTeam.setGoalsAgainst(lineScanner.nextInt());

あなたはそれを見つけられますか?#wins、#drawns、...などを読み取り、それらをwondrawnlostgoalsForgoalsAgainstに格納しますが、Teamオブジェクトを作成する場合は、スキャナーからNEXT値を読み取ります。だから基本的に、あなたはいつも一行おきに読むでしょう!すべてを削除しますが、代わりにこのセクションを保持します。

        Team aTeam = new Team(lineScanner.next());
        aTeam.setWon(lineScanner.nextInt());
        aTeam.setDrawn(lineScanner.nextInt());
        aTeam.setLost(lineScanner.nextInt());
        aTeam.setGoalsFor(lineScanner.nextInt());
        aTeam.setGoalsAgainst(lineScanner.nextInt());

したがって、上記に基づいて、入力ファイルの各行には、 Stringintintintintint
が必要ですが、気付いた場合、入力ファイルの最初の行は次のようになります。

Scottish League Division 1,10

これは文字列intintです。これらを修正すれば、うまくいくはずです。これは私の観察であり、実際にはコードを実行していません。だから私は何かが足りないかもしれません。これらを修正しても問題が解決しない場合は、お知らせください。

編集(2):
コードを変更して修正しました。私はこの入力に対してそれを実行しました:

Scottish League Division 1,10
Airdrie United ,3,2,11,14,25
Clyde          ,5,7,4,21,17
Dundee         ,7,2,7,21,18
Gretna         ,10,3,3,43,20
Hamilton Acas  ,7,5,4,19,20
Livingstone    ,6,6,4,21,15
Partick Thistle,8,4,4,25,29
Queen of South ,3,3,10,11,31
Ross County    ,4,4,4,14,24
St Johnstone   ,6,6,4,26,16


そしてそれはうまくいきます。他に問題があれば教えてください。

import java.io.*;
import java.util.*;

/**  
 * Class League - An instance of this class represents the teams in a
 * football (or similar) league. It provides a class method for creating
 * a new instance of League by reading the data for the teams from a CSV
 * file.
 * 
 * @author Lewis Jones 
 * @version 1.0
 */

public class League
{
   /* instance variables */
   private String name;  // The name of the league
   private Team[] teams; // An array to hold the teams in the league

   /**
    * Constructor for objects of class League. It sets the name of the league
    * to the String object provided as the first argument and initialises teams
    * to an array of the size provided as the second argument. This constructor 
    * is private as it is intended for use only by the class method loadLeague().
    */
   private League(String aName, Team[] teams)
   {
      super();
      this.name = aName;
      this.teams = teams;
   }

   /* class method */
   /**
    * This method creates a new League object by reading the required details from
    * a CSV file. The file must be organised as follows:
    *     name(String), number of teams (int)
    *     team name(String), won(int), drawn(int), lost(int), for(int), against    (int)
    *        and so on for each team
    * Having created the new League object the method should create all the Team 
    * objects (using the data in the file to set their attributes) and add them 
    * to the teams array.
    */
   public static League loadLeague()
   {
      League theLeague = null;
      String pathname = OUFileChooser.getFilename();
      File aFile = new File(pathname);
      Scanner bufferedScanner = null;

      try
      {
         String leagueName;
         int numberOfTeams;

         String teamName;
         int won;
         int drawn;
         int lost;
         int goalsFor;
         int goalsAgainst;
         Scanner lineScanner;
         String currentLine;
         bufferedScanner = new Scanner(new BufferedReader(new FileReader (aFile)));    
         boolean firstLine = true;
         List<Team> teamsList = new ArrayList<Team>();
         Team[] teams = null;
         while (bufferedScanner.hasNextLine())
         {
            currentLine = bufferedScanner.nextLine();
            lineScanner = new Scanner(currentLine);
            lineScanner.useDelimiter(",");

            if (firstLine) {
                // you originally used "bufferedScanner" which actually 
                // gets the values on the next line, not the current line
                leagueName = lineScanner.next();
                numberOfTeams = lineScanner.nextInt();
                firstLine = false;
                continue;
            }

            Team aTeam = new Team(lineScanner.next());
            aTeam.setWon(lineScanner.nextInt());
            aTeam.setDrawn(lineScanner.nextInt());
            aTeam.setLost(lineScanner.nextInt());
            aTeam.setGoalsFor(lineScanner.nextInt());
            aTeam.setGoalsAgainst(lineScanner.nextInt());
            teamsList.add(aTeam);

         }
         teams = teamsList.toArray(new Team[]{});
         theLeague = new League(leagueName, teams);
      }  
      catch (Exception anException)
      {
         System.out.println("Error: " + anException);
      }
      finally
      {
         try
         {
            bufferedScanner.close();
         }
         catch (Exception anException)
         {
            System.out.println("Error: " + anException);
         }
      }
      return theLeague;
   }

   /* instance methods */

   /**
    * Displays the league table in tabular format to the standard output
    */
   public void display()
   {
      System.out.println(this.name);
      System.out.format("%20s %2s %2s %2s %2s %2s %2s %    2s\n","","P","W","L","D","F","A","Pt");
      for (Team eachTeam : this.teams)
      {
         System.out.format("%20s %2d %2d %2d %2d %2d %2d %2d\n",
                       eachTeam.getName(), eachTeam.getPlayed(), 
                       eachTeam.getWon(), eachTeam.getDrawn(), 
                       eachTeam.getLost(),eachTeam.getGoalsFor(), 
                       eachTeam.getGoalsAgainst(), eachTeam.getPoints());        
      }
   }

   /**
    * Arrange the elements of teams in their natural order. This will only
    * work if a natural order has been defined for the class Team.
    */
   public void sort()
   {
      // to be written later...
   }
}


于 2013-02-01T01:41:19.747 に答える