gpt4 book ai didi

java - 实现MVC

转载 作者:行者123 更新时间:2023-12-02 10:44:40 26 4
gpt4 key购买 nike

我正在为我的类使用 MVC 实现代码,但是我遇到了一个我似乎无法弄清楚的错误。我应该更改的作业的唯一部分是模型、 View 和 Controller ,因此其余的类已经为我们完成了。

当我运行代码时, Controller 中出现错误:

“错误:不兼容的类型:学生无法转换为字符串 view.DisplayOnButton(model.getInfoForStudent(0), 0);"

如何解决这个问题?

这是我所拥有的:

Controller -

public class Controller
{
Model model;
View view;

public Controller(Model model, View view)
{
this.model = model;
this.view = view;
SetViewFromModel();
}

public void SetViewFromModel()
{
view.DisplayOnButton(model.getInfoForStudent(0), 0);
view.DisplayOnButton(model.getInfoForStudent(1), 1);
view.DisplayOnButton(model.getInfoForStudent(2), 2);
}
}

型号 -

    public class Model
{
ArrayList<Student> sts = new ArrayList<>();

public Model()
{
//creates 3 students
MailAddress addr1 = new MailAddress("107 W College Avenue", "State College", "PA", 16801);
Student st1 = new Student("Emily", "Smith", 20, addr1);
MailAddress addr2 = new MailAddress("200 W College Avenue", "State College", "PA", 16801);
Student st2 = new Student("Mary", "Doe", 20, addr2);
MailAddress addr3 = new MailAddress("300 W College Avenue", "State College", "PA", 16801);
Student st3 = new Student("John", "Doe", 20, addr3);
//add them to the array of students
sts.add(st1);
sts.add(st2);
sts.add(st3);
}

public Student getInfoForStudent (int studentIndex)
{
return sts.get(studentIndex);
}
}

查看 -

public void DisplayOnButton(String infoToDisplay, int onButton)
{
mf.getIp().DisplayOnButton(infoToDisplay, onButton);
}

最佳答案

您的方法 DisplayOnButton 需要一个字符串,而您正在传递一个 Student,您必须转换您的 getInfoForStudent 以返回字符串或将 Student 转换为字符串。

我建议您为您的邮件和学生覆盖 toString() ,以便它创建一个包含您期望的信息的字符串。

例如:

public class Student {
private final String name;
private final String surname;
private final int age;
private final MailAddress mailAddress;

public Student(String name, String surname, int age, MailAddress mailAddress) {
this.name = name;
this.surname = surname;
this.age = age;
this.mailAddress=mailAddress;
}

@Override
public String toString() {

return String.format("name: %s surname:%s age:%d mail address:%s", name, surname, age, mailAddress);
}
}

您必须对 mailAddress 执行类似的操作,因此您的 getInfoForStudent 如下所示:

 public String getInfoForStudent (int studentIndex)
{
return sts.get(studentIndex).toString();
}

关于java - 实现MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52676229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com