所以我将学生(它们是对象)添加到我的arrayList中,在代码的开头我会让用户添加尽可能多的学生+学生数,直到他们输入空白。一旦他们输入空白,我的程序会打印出所有学生和他们的学生编号。打印出学生及其号码后,系统会要求用户提供搜索字词。然后该程序将打印出所有具有所述搜索词的学生。我的代码中的所有内容都与将搜索字词与我ArrayList
这是我到目前为止所提出的:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<Student>();
System.out.print("name: ");
String name = reader.nextLine();
while (!name.equals("")) {
System.out.print("studentnumber: ");
String studentNumber = reader.nextLine();
students.add(new Student(name, studentNumber));
System.out.print("name: ");
name = reader.nextLine();
}
for (Student prs : students ) {
System.out.println(prs);
}
System.out.println("Give search term: ");
String searchTerm = reader.nextLine();
System.out.println("Result: ");
for (Student prs : students) {
if (prs.contains(searchTerm)) {
System.out.println(prs);
}
}
}
}
所以我的问题是如何修复代码行
for (Student prs : students) {
if (prs.contains(searchTerm)) {
System.out.println(prs);
}
}
让它发挥作用。
感谢您的协助。
答案 0 :(得分:1)
像这样修改您的学生班,无需更改其他代码,只需将其查看为自定义包含方法
即可package com.tried;
public class Student {
String name;
String studentNumber;
public Student(String name2, String studentNumber) {
this.name=name2;
this.studentNumber=studentNumber;
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public boolean contains(String term){
System.out.println(this.studentNumber+"and"+this.name);
if(this.studentNumber.contains(term) || this.name.contains(term)){
return true;
}
return false;
}
@Override
public String toString() {
return "Student [name=" + name + ", studentNumber=" + studentNumber + "]";
}
}
答案 1 :(得分:0)
假设您正确覆盖了Student类的toString方法,请更改
for (Student prs : students) {
if (prs.contains(searchTerm)) {
System.out.println(prs);
}
与
for (Student prs : students) {
if (prs.toString().contains(searchTerm)) {
System.out.println(prs);
}