Java 如何从双链接列表中搜索int键?
键是来自用户的输入。 我试图比较int键和stringid,看看它们是否相等。 如果字符串id==int键。然后返回这个链接。 否则,我想比较列表中的所有IDJava 如何从双链接列表中搜索int键?,java,doubly-linked-list,Java,Doubly Linked List,键是来自用户的输入。 我试图比较int键和stringid,看看它们是否相等。 如果字符串id==int键。然后返回这个链接。 否则,我想比较列表中的所有ID 1. Add a student to records 2. Remove a student from records 3. Search a student from records 4. Display all students in records 5. Quit 当我输入3个学生时,只比较第一个和最后一个。 我怎样才能修好它?
1. Add a student to records
2. Remove a student from records
3. Search a student from records
4. Display all students in records
5. Quit
当我输入3个学生时,只比较第一个和最后一个。
我怎样才能修好它?谢谢你的帮助:)
公共链接搜索学生(int键)
{
链接温度=新链接(空,空);
温度=光标;
int idNumber=0;
如果(大小>=键){
System.out.println(“准备搜索…”);
对于(int i=0;i”+键);
System.out.println(“id-->”+temp.getId());
idNumber=Integer.parseInt(temp.getId());
if(idNumber==键)
System.out.println(“你找到了!”);
其他的
temp=cursor.next;
}
}
返回温度;
}
您可以尝试将字符串与int匹配
if(temp.getId().equals(key+""))
System.out.println("You found it!");
还是这个
String sKey=key+"";
if(skey.equals(temp.getId())
System.out.println("You found it!");
问题在于,您没有在循环内更改
temp
或游标
变量。我只能猜测cursor
在您的类中是什么意思,但如果您将其视为列表的标题,那么您需要在每次迭代中更改temp
。另外,当您发现元素的id
等于key
时,我想您应该停止搜索。请参阅下面的代码
public Link searchStudent(int key) {
Link temp = cursor;
int idNumber = 0;
if(size >= key) {
System.out.println("Ready to Search...");
for(int i = 0; i < size; i++) {
System.out.println("key -> " + key);
System.out.println(" id -> " + temp.getId());
idNumber = Integer.parseInt(temp.getId());
if(idNumber == key) {
System.out.println("You found it!");
break;
} else {
// Here!
temp = temp.next;
}
}
}
return temp;
}
公共链接搜索学生(int键){
链接温度=光标;
int idNumber=0;
如果(大小>=键){
System.out.println(“准备搜索…”);
对于(int i=0;i”+键);
System.out.println(“id->”+temp.getId());
idNumber=Integer.parseInt(temp.getId());
if(idNumber==键){
System.out.println(“你找到了!”);
打破
}否则{
//这里!
温度=下一个温度;
}
}
}
返回温度;
}
您需要提供更多的代码。searchStudent
方法中有对字段的引用,这些字段显然是在此方法之外初始化的。
public Link searchStudent(int key) {
Link temp = cursor;
int idNumber = 0;
if(size >= key) {
System.out.println("Ready to Search...");
for(int i = 0; i < size; i++) {
System.out.println("key -> " + key);
System.out.println(" id -> " + temp.getId());
idNumber = Integer.parseInt(temp.getId());
if(idNumber == key) {
System.out.println("You found it!");
break;
} else {
// Here!
temp = temp.next;
}
}
}
return temp;
}