Encountering "error: incompatible types: unexpected return value" and "error: 'void' type not allowed here" - java

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.

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().

Related

JAVA Created two objects of each class with complete data using a constructor but getting an error

I'm trying to create two objects of each Man and Woman class with complete data using a constructor, with constructor that have all possible parameters.
I'm getting an error stating :
"invalid method declaration; return type required".
My code :
public class Solution {
public static void main(String[] args) {
Man man1 = new Man();
System.out.println(man.name + "" + man.age + "" + man.address);
Man man2 = new Man();
System.out.println(man.name + "" + man.age + "" + man.address);
Woman woman1 = new Woman();
System.out.println(woman.name + "" + woman.age + "" + woman.address);
Woman woman2 = new Woman();
System.out.println(woman.name + "" + woman.age + "" + woman.address);
//write your code here
}
private String name = "Mark";
private int age = 23;
private String address = 16527;
public Man(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public Woman(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;//write your code here
}
}
Can someone please help me :(
Your class is named Solution which means that your constructor can be named only Solution. Create separate classes named Man and Woman and then add your constructors there.
Also, since you are creating an object using default constructor, make sure to add them too in the above mentioned classes.
In order to call new Man() or new Woman(), you need to create an empty constructor for each class. Alternatively, you can have no constructor at all in the class and let java construct the default constructor.
Based on your code, you can only initialize them via the constructor that you have create which are new Man("Mark", 23, "16527") and new Woman("Mary", 23, "16527")
May be your code will be like this:
public class Solution {
public static void main(String[] args) {
Man man1 = new Man(); // first way to create object
Man man2 = new Man("dhiraj",28,"Indore"); // second way to create object
System.out.println(man2.name + "" + man2.age + "" + man2.address);
Woman woman1 = new Woman(); // first way to create object
Woman woman2 = new Woman("dhiraj",28,"Indore"); // second way to create object
System.out.println(woman2.name + "" + woman2.age + "" + woman2.address);
//write your code here
}
}
class Man
{
private String name, address;
private int age;
public Man()
{
}
public Man(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
}
class Woman
{
private String name, address;
private int age;
public Woman()
{
}
public Woman(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;//write your code here
}
}
It seems you are new to Java. The code you've provided has a lot of mistakes.
(For ex:) Constructor should have the same name as the class
While defining an object using a constructor parameters should be passed as arguments(If not default constructor will be called) and etc. Please refer This link to get more idea about java classes and objects.
Your main problem, the cause of the error invalid method declaration; return type required is that you are putting the constructor for Man and Woman inside another (Solution) class. They should be defined in their own class. This error you're getting means that the compiler thinks there is a regular method declaration without a return type. It just thinks you made a method called Man(with some arguments) and a method called Woman (with some arguments).
Additionally, if you want that data to actually be part of the Man or Woman class, you should make sure it becomes part of those objects. You could make a constructor with those arguments or add it through setter methods later. The data won't magically appear in those objects just by constructing them with an empty constructor.

it's print null in console when I run a program in Java

`
package Stuff;
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
studentName = name;
studentAge = age;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}
`
I Don't Know where is the wrong in code the console print me (null) when i request student1.printName() and 0 When i request Student.printAge()
Your variable assignments in the constructor are the wrong way around.
You are assigning the variables in the constructor in wrong way. The correct way will be:
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
If you auto-generate the constructors then it will look like this, which is more common convention:
public Student(String name,int age){
this.name = name;
this.age = age;
}
You messed up the initialization part studentname = name and studentage = age the right way of initialization is given down
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}
The constructor should be like
public Student(String studentName,int studentAge){
this.name = studentName;
this.age = studentAge;
}
I highly recommend that you have a look at this article on associativity in Java.
Basically, when you assign a value to a variable using the = operator, the statement is carried out from right to left. Hence, the outcome of the expression on the Right Hand Side is assigned to the variable on the Left Hand Side.
Hence, int a = 5+5 means that the outcome of 5+5 is stored in variable a. This is also why studentName = name assigns the value of name (which is the default value of the String type - null) to studentName.
It is also important to note that null is a keyword in Java, and if you print null like this:
System.out.println(null)
A Syntax Error will be thrown (which is for a different reason).
EDIT - At the time of typing this out, there was only one answer, and not explanatory in any way. Now, I see there are more. Although the other answers may tell you what to do, I figured that this answer would tell you how to think in Java, so that you make no such mistakes again.

Writing a constructor, takes an enum argument from a different class

I am trying to program an AI for a game and I wanna be able to set different modes for players.
Here is my enum in Type.java:
public enum Type {
Human,Random,Minimax
}
And here is the constructor in player.java to set the type of the player:
public Player(String name, Type e ) {
this.name = name;
this.Type = e;
}
Now Eclipse says "Type cannot be resolved or is not a field."
What should I do? Both files are in the same package.
Now Eclipse says "Type cannot be resolved or is not a field."
That's telling you that the problem it has is with the Type in the line:
this.Type = e;
// ^---- This one
Declare a field in Player if you haven't already:
private Type type;
...and then make sure you're using that field's name in the constructor:
this.type = e;
Note I've used lower case for the field name. This is the overwhelming convention in Java, and matches what you did with the field name.
It looks like there is no field Type in your player class.
Something like this would work
class Player {
String name;
Type e;
public Player(String name, Type e) {
this.name = name;
this.e = e;
}
}
Main.java:
public class Main
{
public static void main(String[] args)
{
Player player = new Player( "test", Type.Human );
System.out.println( player.toString() );
}
}
Type.java
public enum Type {
Human, Random, Minimax
}
Player.java
public class Player
{
private String name;
private Type type;
public Player(String name, Type e)
{
this.name = name;
this.type = e;
}
public String toString()
{
return name + " " + type.toString();
}
}
If you compile and run that, toString will return this:
test Human

Java getClass().getName() it returns the class not the name

The output was Card Card. It was suppose to be unknown Jane. How do i fix this? I tried to fix it with Card.getClass().getName() but that gives me another error non-static method getClass() cannot be referenced from a static context.
public class Card
{
private String name;
public Card()
{
name = "unknown";
}
public Card(String name1)
{
name = name1 ;
}
public String getName()
{
return name;
}
public String toString()
{
return getClass().getName();
}
}
public class CardTester
{
public static void main(String[] args)
{
Card card ;
card = new Card() ;
System.out.println(card) ;
System.out.println("unknown WAS EXPECTED") ;
card = new Card("Jane") ;
System.out.println(card) ;
System.out.println("Jane WAS EXPECTED") ;
}
}
Your toString() method prints the name of the class of the object:
return getClass().getName();
The object is an instance of Card, so its class is Card.class, whose name is Card. You want to print the value of the name field. So you simply need
return name;
getClass() returns the Class object representing the "Card" class; therefore the code does not refer to Card#getName method, but rather to Class#getName which dutifully returns "Card".
Simply remove getClass():
public String toString()
{
return getName();
}
The previous error (wrt "static") was using Card.getName() - don't prefix a type to invoke an instance method.

Java class "cannot be resolved to a type"

This is the error I'm getting:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
TeamLeader cannot be resolved to a type
at TeamLeadDemo.main(TeamLeadDemo.java:26)
This is my code:
import java.util.Scanner;
public class Employee {
public String empName, empNumber, hireDate;
public class TeamLeadDemo {}
public Employee(String empName, String empNumber, String hireDate) {
this.setEmpName(empName);
this.setEmpNumber(empNumber);
this.setHireDate(hireDate);
}
public void setEmpName(String empName) {
this.empName = empName;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public void setHireDate(String hireDate) {
this.hireDate = hireDate;
}
public String getEmpName() {
return empName;
}
public String getEmpNumber() {
return empNumber;
}
public String getHireDate() {
return hireDate;
}
public class ShiftSupervisor extends Employee {
public double annualSalary, annualProduction;
//constructor
public ShiftSupervisor(String empName, String empNumber,
String hireDate, double annualSalary,
double annualProduction) {
super(empName,empNumber, hireDate);
this.setAnnualSalary(annualSalary);
this.setAnnualProduction(annualProduction);
}
public double getAnnualSalary() {
return annualSalary;
}
public double getAnnualProduction() {
return annualProduction;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
public void setAnnualProduction(double annualProduction) {
this.annualProduction = annualProduction;
}
public String toString() {
return "Name: "+ getEmpName() + "\nEmpID: "+ getEmpNumber()
+ "\nHire Date: "+ getHireDate() + "\nAnnual Salary: "
+ annualSalary + "\nProduction: "+ annualProduction;
}
public class employeeStart {
public void main(String[] args) {
String name, id, date;
double sal, prod;
//create scanner object
Scanner keyboard = new Scanner(System.in);
//inputting data
System.out.println("Enter Name: ");
name = keyboard.nextLine();
System.out.println("Enter id: ");
id = keyboard.nextLine();
System.out.println("Enter Hire Date: ");
date = keyboard.nextLine();
System.out.println("Enter Annual: ");
sal = keyboard.nextDouble();
System.out.println("Enter production: ");
prod = keyboard.nextDouble();
//instantiating object
ShiftSupervisor pw = new ShiftSupervisor(name, id, date, sal, prod);
//outputting data
System.out.println("Employee Details: \n" + pw);
}
}
public class TeamLeader {
public double monthlyBonus;
public int minTraining, trainingPresent;
public TeamLeader(double monthlyBonus, int minTraining, int trainingPresent) {
this.setMonthlyBonus(monthlyBonus);
this.setMinTraining(minTraining);
this.addtrainingPresent(trainingPresent);
}
public void setMonthlyBonus(double monthlyBonus) {
this.monthlyBonus = monthlyBonus;
}
public void setMinTraining(int minTraining) {
this.minTraining = minTraining;
}
public void setTrainingPresent(int t) {
trainingPresent = t;
}
public void addtrainingPresent(int hours) {
trainingPresent += hours;
}
public double getMonthlyBonus() {
return monthlyBonus;
}
public int getMinTraining() {
return minTraining;
}
public int getTrainingPresent() {
return trainingPresent;
}
public String toString() {
return "Bonus: "+ getMonthlyBonus() + "\nMinimum Training: "
+ getMinTraining() + "\nAttendence: "+ getTrainingPresent();
}
}
}
}
In addition, I declared this in a separate class:
import java.util.Scanner;
public class TeamLeadDemo extends Employee {
public TeamLeadDemo(String empName, String empNumber, String hireDate) {
super(empName, empNumber, hireDate);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
double sal;
int min, atten;
//create scanner object
Scanner keyboard = new Scanner(System.in);
//inputting data
System.out.println("Enter minimum training: ");
min = keyboard.nextInt();
System.out.println("Enter id: ");
atten = keyboard.nextInt();
System.out.println("Enter Bonus: ");
sal = keyboard.nextDouble();
//instantiating object
ShiftSupervisor pw = new TeamLeader(sal, min, atten);
//outputting data
System.out.println("Employee Details:\n" + pw);
}
}
What is causing this error and how might I resolve it?
EDIT: Indentation, whitespace, naming conventions and readability issues have been somewhat addressed.
If this problem is with maven project then right-click Maven > Update Project should solve the problem
The problem is that TeamLeader appears to be an inner class (hard to tell, your indentation is bad), and since it's not static, you can't instantiate it by itself.
You either need to make TeamLeader its own class, or make it a static class and instantiate it as Employee.TeamLeader (or whatever the parent class is, your indentation is really not helpful here).
Your exception message says this
Exception in thread "main" java.lang.Error: Unresolved compilation problem: TeamLeader cannot be resolved to a type
This means that you have tried to run a program that used some class that has not compiled correctly.
Go back and fix the compilation error(s).
It is not clear what the fix for the compilation error should be, but the error is saying that it cannot find a class called TeamLeader. Perhaps it doesn't exist. Perhaps it is in a different package. Perhaps you haven't compiled it. Perhaps something else.
Looking at the code, I think the problem is that you have defined two distinct classes called TeamLeadDemo, one as a nested class of Employee and the second as a top-level class. Furthermore the second of these is attempting to use TeamLeader ... but the TeamLeader class that you have actually declared is nested 2 levels down in Employee; i.e. its real name is Employee.ShiftSupervisor.TeamLeader.
This is all a bit nonsensical.
By the look of it, you defined a whole bunch of classes in the same file ("Employee.java") without much understanding of what it means to put one class inside another. Most likely, each of those classes should be declared in its own file. And most likely you should just delete the nested TeamLeadDemo class.
That error can appear also if you create the inner class by moving it from somewhere, and with reorganization, you put the import line for that inner class in its outer class file. After that the inner class cannot be resolved to a type anywhere. Automatic insert of import won't help.
You have not published the import section of the outer class and we cannot check that variant. Check for it, and if the excessive import is there, remove it.
And if you work in Eclipse, it is very probable you need to clean the project after that.

Categories

Resources