帮忙看看,红色处有错误
程序一:(红色处出现异常)package test;
import java.util.Scanner;
public class Test {
/*int[] array=new int[]{2,3,1,5,4};*/
int[] array=new int[5];
public void input() {
Scanner scan=new Scanner(System.in);
for(int i=0;i<array.length;i++)
array[i]=scan.nextInt();
scan.close();
}
public void insertSort(){
for(int i=1; i<array.length; i++){
if(array[i]<array[i-1]){
int temp=array[i];
array[i]=array[i-1];
int j=i-1;
for (; j>=0 && temp<array[j]; --j)
array[j+1] = array[j];
array[j+1] = temp;
}
}
}
public int search(int key){
int low=0,high=array.length-1;
while(low<high){
int mid=(low+high)/2;
if(array[mid]<key) low=mid+1;
else if(array[mid]>key) high=mid-1;
else return mid;
}
return -1;
}
public void print(){
for(int i=0; i<array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
}
public int scan(){
System.out.println("输入查找的元素,返回在排序后该元素的数组下标");
Scanner s=new Scanner(System.in);
int key=s.nextInt();
s.close();
return key;
}
public static void main(String[] args){
try{
Test test=new Test();
test.input(); //可选
test.insertSort();
test.print();
int key=test.scan(); //可选
int index=test.search(key); //可选 /*System.out.println(test.search(2);*/
if(index<0)
System.out.println("未找到!");
else System.out.println(index);
}catch(Exception e){
System.out.println("出现异常!");
}finally{
System.out.println("结束!");
}
}
}
程序二:(已解决)
package test;
import java.util.*;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student (String name, int age)
{ this.name=name; this.age=age; }
public boolean equals(Object o) {
if(this==o) return true;
if(!(o instanceof Student)) return false;
Student other=(Student)o;
return (other.name==this.name && other.age==this.age) ? true : false;
}
public int hasCode(){
int result;
result=(name==null ? 0 : name.hashCode());
return result*124+age*23;
}
public int compareTo(Student stu) {
if((stu.name)>0) return 1;
if((stu.name)<0) return -1;
if(age>stu.age) return 1;
if(age<stu.age) return -1;
return 0;
}
public static void main(String[] args) {
Set<Student> set=new TreeSet<Student>();
set.add(new Student("Tom",12));
set.add(new Student("Jack",18));
Iterator<Student> iter=set.iterator();
while(iter.hasNext()){
Student stu=(Student)(iter.next());
System.out.println("Student’s name:"+stu.name+"age:"+stu.age);
}
}
}
Exception in thread "main" java.lang.ClassCastException: test.Student cannot be cast to java.
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at test.Student.main(Student.java:30)
[[it] 本帖最后由 c_acceleration 于 2008-6-14 17:58 编辑 [/it]]
[[it] 本帖最后由 c_acceleration 于 2008-6-15 13:12 编辑 [/it]]