Why do I get a ClassCastException and how do I fix it?

ぐ巨炮叔叔 提交于 2020-01-05 08:09:37

问题


Why do I get a ClassCastException and how do I fix it? I got the following Exception message. Code is below:

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)

Here is my code:

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

回答1:


The problem is that you are reading in the scores as String, and trying to put the scores in an ArrayList of Integer.

You need to either read the score as an integer, or parse the score into an integer.

See API links below

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)



来源:https://stackoverflow.com/questions/15646686/why-do-i-get-a-classcastexception-and-how-do-i-fix-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!