英文:
Encountering "error: incompatible types: unexpected return value" and "error: 'void' type not allowed here"
问题
public void getName() {
// TODO: Assign parameter to instance field
return name;
}
public void setName(String name) {
// TODO: Assign parameter to instance field
this.name = name;
}
public double getGPA() {
// TODO: Assign parameter to instance field
return gpa;
}
public void setGPA(double gpa) {
// TODO: Assign parameter to instance field
this.gpa = gpa;
}
英文:
I'm still very new to Java and I've been stuck on this lab question for my Java course for a while, and I thought everything was good once I got to this point with my code:
public class Student {
// TODO: Build Student class with private fields and methods listed above
// private variables
private String name;
private double gpa;
// TODO: Define two private member fields
// default constructor
public Student() {
name = "Louie";
gpa = 1.0;
}
public Student(String name, double gpa) {
this.name = name;
this.gpa = gpa;
}
public void getName() {
// TODO: Assign parameter to instance field
return name;
}
public void setName(String name) {
// TODO: Assign parameter to instance field
this.name = name;
}
public double getGPA() {
// TODO: Assign parameter to instance field
return gpa;
}
public void setGPA(double gpa) {
// TODO: Assign parameter to instance field
this.gpa = gpa;
}
// TODO: Add three more methods
public static void main(String[] args) {
Student student = new Student();
System.out.println(student.getName() + "/" + student.getGPA());
student.setName("Felix");
student.setGPA(3.7);
System.out.println(student.getName() + "/" + student.getGPA());
}
}
But then I got these errors:
Student.java:21: error: incompatible types: unexpected return value
return name;
^
Student.java:44: error: 'void' type not allowed here
System.out.println(student.getName() + "/" + student.getGPA());
^
Student.java:48: error: 'void' type not allowed here
System.out.println(student.getName() + "/" + student.getGPA());
I tried googling the errors to see how others solved these, but I would get rid of one error and encounter a completely different one. I am unsure how to go about solving the "unexpected return value" error. But as for the "void type not allowed here" I tried removing 'void' from the 'public static void main' as I saw that recommended to others encountering the same issue but this caused other errors.
The expected outcome for the code should be something like:
Louie/1.0
Felix/3.7
I am confused as to why the main class is having problems as this part of the code was already filled in when I started the lab.
答案1
得分: 3
在第21行,您正在返回类型为String
的name
,但是您的getName()
函数的签名是public void getName()
。要解决此问题,请将void
更改为String
:public String getName()
。
英文:
On line 21 you are returning name
of type String
but your getName()
function's signature is public void getName()
. To fix this change void
to String
: public String getName()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论