Java 为什么我会得到ClassCastException以及如何修复它?
为什么我会得到ClassCastException以及如何修复它?我收到了以下异常消息。代码如下: 线程“main”java.lang.ClassCastException中的异常Java 为什么我会得到ClassCastException以及如何修复它?,java,casting,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) 这是我的密码: imp
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 );
}
}
import java.util.*;
公开课高分{
公共静态void main(字符串参数[])
{
ArrayList name=新的ArrayList();
ArrayList分数=新建ArrayList();
初始化(名称、分数);
排序(姓名、分数);
显示(姓名、分数);
}
公共静态无效初始化(ArrayList名称、ArrayList分数)
{
扫描仪输入=新扫描仪(System.in);
对于(int i=0;i<5;i++)
{
System.out.println(“输入分数的名称”+(i+1)+:”;
name.add(in.next());
System.out.println(“为分数输入分数”+(i+1)+“:”;
添加(in.next());
}
}
公共静态无效排序(ArrayList名称、ArrayList分数)
{
对于(int i=0;i<(4);i++)
{
对于(int j=(i+1);j<(3);j++)
{
/*第32行-->*/if(scores.get(i)
问题在于,您正在以字符串的形式读取分数,并试图将分数放入整数的数组列表中
您需要将分数读取为整数,或者将分数解析为整数
请参阅下面的API链接
问题在于,您正在以字符串的形式读取分数,并试图将分数放入整数的数组列表中
您需要将分数读取为整数,或者将分数解析为整数
请参阅下面的API链接
为什么从排序
方法而不是初始化
引发异常?为什么从排序
方法而不是初始化
引发异常?