I'm trying to create a code that gets the response:
Event recorded at 10:53, datum = 45
However, at the moment, I'm getting the output, 'java: 'void' type not allowed here', but I;m not too sure what I can add to the getEventTime and getEventDatum to make it valid.
class EventInformation{
String eventTime;
int eventDatum;
EventInformation(String eventTime, int eventDatum){
this.eventTime = eventTime;
this.eventDatum = eventDatum;
}
public void getEventTime(){
String getEventTime = eventTime;
}
public void getEventDatum(){
int getEventDatum = eventDatum;
Here is the additional code from the main method:
EventInformation e = new EventInformation("10:53",45);
System.out.println("Event recorded at " e.getEventTime()
", datum = " e.getEventDatum());
Any help at all is greatly appreciated!
CodePudding user response:
void
means that your method returns nothing, but you do want to return something - a String
for getEventTime()
and an int
for getEventDatum()
. Thus, your methods should look like this:
public String getEventTime() {
return eventTime;
}
public int getEventDatum() {
return eventDatum;
}
But you can use a better style:
What you are trying to achieve here is to convert an EventInformation
to a String
. Because converting any Object
to a String
to print it out is a common problem in java, there is a method toString()
in the class Object
, which you can override:
public class EventInformation {
String eventTime;
int eventDatum;
EventInformation(String eventTime, int eventDatum){
this.eventTime = eventTime;
this.eventDatum = eventDatum;
}
public String toString() {
return "Event recorded at " eventTime
", datum = " eventDatum;
}
}
Now, you can directly print out the EventInformation using
EventInformation e = new EventInformation("10:53",45);
System.out.println(e);
and java will take care of converting this EventInformation
to a String
using the toString()
method.
The advantage is that you can now print an EventInformation
from everywhere in your code without creating the String
again there.
CodePudding user response:
If the method returns VOID it means that it does not return anything. Let's start with getters and setters java-getters-and-setters