这里的第一个问题..我有一个简单的程序,包括单独的课程(学生,教师,书籍,教室),您可以按名称,电子价格,房间容量等进行搜索。这些对象都存储在Bag类中。我有一个单独的Object类来扩展学生,教师等类。我不确定我在主Bag类中的演员出了什么问题。任何帮助将不胜感激。
package Bag;
import java.util.ArrayList;
public class Main {
private static ArrayList<Object> collection = new ArrayList();
public static void main (String[] args) {
Student student = new Student("Sameet", 1, 4);
Faculty faculty = new Faculty("Chen", 1000.00, 1);
Classroom classRoom = new Classroom(1, 10);
Book book = new Book("Harry Potter", 10);
collection.add(student);
collection.add(faculty);
collection.add(classRoom);
collection.add(book);
}
public void insert(Object obj){
collection.add(obj);
}
public Student searchForStudent(int ID){
for (Object obj: collection){
if (obj instanceof Student && (Student)obj.getID() == ID){
return (Student)obj;
}
}
}
public Faculty searchForFaculty(String name){
for (Object obj : collection) {
if (obj instanceof Faculty && (Faculty)obj.getName() == name) {
return (Faculty)obj;
}
}
}
public Classroom searchForClass(int capacity){
for (Object obj : collection) {
if (obj instanceof Classroom && (Classroom)obj.getCapacity() == capacity) {
return (Classroom)obj;
}
}
}
public Book searchForBook(int price){
for (Object obj : collection) {
if (obj instanceof Book && (Book) obj.getPrice() == price) {
return (Book)obj;
}
}
}
}
答案 0 :(得分:1)
实际上,这段代码存在很多问题。
1)铸件处理不当:
(Faculty) obj.getName() // not working
((Faculty) obj).getName() // this is the proper way of casting
2)搜索方法中缺少return语句。你应该抛出异常或返回一些东西。我在我的例子中返回了空值。
3)与==
而不是equals()
进行字符串比较。如果要比较字符串是相等而不是相同,则应始终将字符串与equals()
进行比较。 ==
比较对象的标识(非基本类型),如果它们共享相同的内存地址,则返回true。
4)存在一些设计问题,最好将每个搜索方法保存在相关类中,而不是将所有搜索方法都收集在一个类中。但我真的不知道你想要解决的目的和任务,所以让我们专注于其他问题。
代码中修复了所有编译时问题:
import java.util.ArrayList;
public class Bag {
private static ArrayList<Object> collection = new ArrayList();
public static void main(String[] args) {
Student student = new Student("Sameet", 1, 4);
Faculty faculty = new Faculty("Chen", 1000.00, 1);
Classroom classRoom = new Classroom(1, 10);
Book book = new Book("Harry Potter", 10);
collection.add(student);
collection.add(faculty);
collection.add(classRoom);
collection.add(book);
}
public void insert(Object obj) {
collection.add(obj);
}
public Student searchForStudent(int ID) {
for (Object obj : collection) {
if (obj instanceof Student && ((Student) obj).getId() == ID) {
return (Student) obj;
}
}
return null;
}
public Faculty searchForFaculty(String name) {
for (Object obj : collection) {
if (obj instanceof Faculty && name.equals(((Faculty) obj).getName())) {
return (Faculty) obj;
}
}
return null;
}
public Classroom searchForClass(int capacity) {
for (Object obj : collection) {
if (obj instanceof Classroom && ((Classroom) obj).getCapacity() == capacity) {
return (Classroom) obj;
}
}
return null;
}
public Book searchForBook(int price) {
for (Object obj : collection) {
if (obj instanceof Book && ((Book) obj).getPrice() == price) {
return (Book) obj;
}
}
return null;
}
}