1

ClassCastException が発生する理由とその修正方法を教えてください。次の例外メッセージを受け取りました。コードは以下のとおりです。

Exception in thread "main" java.lang.ClassCastException:

java.lang.String cannot be cast to java.lang.Integer
        at HighScores.sort(HighScores.java:32)
        at HighScores.main(HighScores.java:10)

これが私のコードです:

import java.util.*;


public class HighScores {
    public static void main( String args[] )
    {
        ArrayList<String> names = new ArrayList();
        ArrayList<Integer> scores = new ArrayList();
        initialize( names, scores );
        sort( names, scores );
        display( names, scores );
    }

    public static void initialize( ArrayList names, ArrayList scores )
    {
        Scanner in = new Scanner( System.in );
        for ( int i = 0; i < 5; i++ )
        {
            System.out.println( "Enter the name for score # " + (i + 1) + ": " );
            names.add( in.next() );
            System.out.println( "Enter the score for score # " + (i + 1) + ": " );
            scores.add( in.next() );
        }
    }

    public static void sort( ArrayList<String> names, ArrayList<Integer> scores )
    {
        for ( int i = 0; i < (4); i++ )
        {
            for ( int j = (i + 1); j < (3); j++ )
            {
/*Line 32 -->*/ if ( scores.get( i ) < scores.get( j ) )
                {
                    int tempScore = scores.get( i );
                    scores[i] = scores[j];
                    scores[j] = tempScore;
                    String tempName = names.get( i );

                    names[i] = names[j];
                    names[j] = tempName;

                    scores.add( i, maxValue );
                    scores.remove( j );
                    scores.add( j, temp );

                    String tempName = names.get( i );
                    String maxName = names.get( j );
                    names.remove( i );
                    names.add( i, maxName );
                    names.remove( j );
                    names.add( j, tempName );

                }
            }
        }
    }

    public static void display( ArrayList names, ArrayList scores )
    {
        System.out.println( "Top Scorers: " );
        System.out.println( names );
        System.out.println( scores );
    } 
}
4

1 に答える 1

1

問題は、スコアを として読み込み、Stringスコアを の ArrayList に入れようとしていることですInteger

スコアを整数として読み取るか、スコアを整数に解析する必要があります。

以下の API リンクを参照してください

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt() http://docs.oracle.com/javase/7/docs/api/java/lang /Integer.html#parseInt(java.lang.String)

于 2013-03-26T20:42:11.923 に答える