[英]Find method in Linked List
我有一个名为ll的对象的链表。 我的对象称为“ 学生” ,它具有名称,年级和年龄。 我想创建一个基于学生姓名的查找方法。
import java.util.LinkedList;
import java.util.Scanner;
public class Course {
LinkedList<Object> ll = new LinkedList<Object>();
Scanner s = new Scanner(System.in);
public void addStudent() {
p("Enter the name that you want");
String f = s.nextLine();
Student a = new Student(f);
ll.add(a);
}
public void changeName() { //this method is to change the name of a student
Student student = findStudent();
p("Enter the name that you want");
String newName = s.nextLine();
Student.setName(newName);
}
public void setGrade() { //this method is to put the student's grade
Student student = findStudent();
p("Enter the grade that you want");
int grade = s.nextInt();
Student.setGrade(grade);
}
public void setAge() { //This method is to put the student's grade
Student student = findStudent();
p("Enter the age that you want");
int age = s.nextInt();
Student.setAge(age);
}
public Student findStudent(){
p("Which student do you want to change? Please enter their name:");
String name = s.nextLine();
boolean a=false;
for (int e=0; e<ll.size(); e++) {
if (name.equals(ll(e).name)) {
p("Found the student");
break;
return e;
//Find student in the list - left for the author
} else {
a=true;
}
}
if (a) {
p("Student is not in the list");
Student student = null;
return student;}
}
public String show() {
if (ll!=null) {
for (int i=0; i<ll.size(); i++) {
return "Student(name:" + name + ", age:" + age + ", grade:" + grade + ")";
}
} else {return "There are no students in the list";
}
}
//-------------------------------------------------------------------------
public void p(String x) {
System.out.println(x);
}
public static void main(String[] args) {
p("What do you want to do?");
Course course = new Course();
p("To add a student press 1");
p("To change the name of a student press 2");
p("To set the grade for a student press 3");
p("To set the age of a student press 4");
p("To find a student press 5");
p("To show the students press 6");
p("To get the age of a student press 7");
p("To get the grade of a student press 8");
int a = s.nextInt();
if (a==1) {
addStudent();
} else if (a==2) {
changeName();
}else if (a==3) {
setGrade();
}else if (a==4) {
setAge();
} else if (a==5) {
findStudent();
}else if (a==6) {
show();
} else if (a==7) {
getAge();
} else if (a==8) {
getGrade();
}
new Course();
}
}
在find方法中,它说找不到符号ll(int)。 我该怎么做才能根据我的对象的参数创建查找方法。
要从列表中获取第n个元素,请使用get
方法: ll.get(e)
而不是ll(e)
。
另一方面,您要遍历该列表,并且不重复在链接列表上调用get
更为有效。 相反,您可以这样做:
int e = 0;
for (Student s: ll) {
if (name.equals(s.name)) ....
e++;
}
要使现有方法起作用,您需要更改:
if (name.equals(ll(e).name)) {
至
if (name.equals(ll.get(e).name)) {
我们需要使用get()
方法从列表中获取元素,它不同于数组。
另外,如果您想要一种按姓名查找学生的方法,则可以编写如下代码:
public Student findStudent(String name){
for (int e=0; e<ll.size(); e++) {
if (ll.get(e).name.equals(name)) {
return e;
}
}
//Not found
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.