1
为什么我得到一个ClassCastException,我该如何解决它?我收到以下异常消息。代码如下:为什么我得到一个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);
}
}
见API链接为什么例外是从'sort'方法,而不是'initialise'抛出? – Holloway 2014-03-26 16:12:36