java - 为什么会收到 ClassCastException 以及如何修复它?

标签 java casting

为什么我会收到 ClassCastException 以及如何修复它?我收到以下异常消息。代码如下:

线程“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 );
    } 
}

最佳答案

问题在于您正在以 String 形式读取分数,并尝试将分数放入 Integer 的 ArrayList 中。

您需要将分数读取为整数,或将分数解析为整数。

请参阅下面的 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)

关于java - 为什么会收到 ClassCastException 以及如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15646686/

相关文章:

java.lang.ClassCastException : java. util.Arrays$ArrayList 无法转换为 java.util.ArrayList

java - 如何创建具有 MAVEN 支持的 GWT 项目?

java - TextToSpeech 无法正确停止

sql - DB2 LIKE 运算符的奇怪长度限制

c - 类型转换指针取消引用

swift - 将字符串的 NSObject 转换为 [String]

java - 以图片作为输入,进行灰度化,然后输出

java - JSP访问HashMultimap异常是什么原因

java - 如何在java代码中使用括号