package exercisepack;
public class Student
{
public int num;
public String name;
public int score;
public Student next;
public Student(int nu,String na,int sc,Student ne)
{
this.num=nu;
this.name=na;
this.score=sc;
this.next=ne;
}
public Student()
{}
}
这是我定义的一个学生类,然后我在同一个包下创建一个查找类来实现查找功能。标题上已经说了,所以这里就是要把学生里的各种方法写到查找类里。
package exercisepack;
import exercisepack.Student;
public class Search{
static Student stu;
static int length=1;
static void setNext(Student t)
{
stu=t;
}
static Student getNext()
{
return stu;
}
static void find(int nu)
{
for(int i=1;i<10;i++)
{
Student st=stu;
st=getNext();
if(nu==st.num)
{
System.out.println("学号为"+nu+"的学生成绩为:"+st.score);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu=new Student(1,"stu1",(int)(Math.random()*100),null);
for(int i=1;i<10;i++)
{
setNext(new Student(i+1,"stu"+(i+1),(int)(Math.random()*100),stu));
stu=getNext();
length++;
}
find(1);
System.out.println("长度为"+length);
}
}
我是这样写的,可是我的查找函数死活都不行,我调的时候发现是
for(int i=1;i<10;i++)
{
Student st=stu;
st=getNext();
if(nu==st.num)
{
System.out.println("学号为"+nu+"的学生成绩为:"+st.score);
}
}
这里的问题,这里的st.num始终都没有变过,一直都是第10个学头疼生的信息,我看了整个stu对象,确实是存储了10个学生的信息。这可让我头疼啊,请高手们出谋划策啊,,,谢谢了!
这是因为你Search类里面的
static Student stu;
这是一个static静态属性,是类属性。
for (int i = 1; i < 10; i++) {
setNext(new Student(i + 1, "stu" + (i + 1),
(int) (Math.random() * 100), stu));
stu = getNext();
length++;
}
当你通过for循环,setNext操作后,类属性stu已经被成第10个学生的信息了
用你的查找类继承你的学生类就可以了。
public class Search extends Student {
………………
}
在csdn上看到过哦,你最好看看链表的数据结构,可能对你有帮组
我把你的代码修改了下,你自己看下,希望对你有所帮助:
[code="java"]
public class Student {
private int num;
private String name;
private int score;
private Student next;
public Student(int nu, String na, int sc, Student ne) {
this.num = nu;
this.name = na;
this.score = sc;
this.next = ne;
}
public Student() {
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Student getNext() {
return next;
}
public void setNext(Student next) {
this.next = next;
}
}
[/code]
[code="java"]
package test;
public class Search {
static Student stu;
static int length = 1;
static void find(int nu) {
for (int i = 1; i < 10; i++) {
Student st = stu;
if (nu == st.getNum()) {
System.out.println("学号为" + nu + "的学生成绩为:" + st.getScore());
break;
}
st = st.getNext();
}
}
public static void main(String[] args) {
Student st = new Student(1, "stu1", (int) (Math.random() * 100), null);
stu = st;
for (int i = 1; i < 10; i++) {
st = new Student(i + 1, "stu" + (i + 1), (int) (Math.random() * 100), st);
length++;
}
find(1);
System.out.println("长度为" + length);
}
}
[/code]