Apologies in advance if the title doesn't make any sense. I'm trying to call a function named "emergencyButtonToggled" from a variable called "emergencyButton" but for some reason the code doesn't want to run. The error I am getting is as follows:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method emergencyButtonToggled() is undefined for the type emergencyButton
at emergencyButton.main(emergencybutton.java:10)
My code is as such:
import java.util.*;
public class emergencyButton {
public static void main(String[] args) {
Scanner value = new Scanner(System.in);
System.out.println("Is the emergency button pressed? (Yes/No)");
String button = value.nextLine();
if (button.equals("Yes")) {
System.out.println("The emergency button is pressed.");
emergencyButtonToggled();
} else {
if (button.equals("No")) {
System.out.println("Buzzer is not buzzing");
System.out.println("No emergency");
break;
}
}
}
class emergencyButtonToggled {
public main(String[] args) {
System.out.println("Buzzer is buzzing");
System.out.println("Emergency, Manual Stop");
System.out.println("Emergency, Water Reservoirs empty");
}
}
}
Thank you in advance.
CodePudding user response:
You can't call class. Class is like a group of members. And members can be fields (representing state) or methods (representing actions). So, you can only call class methods.
You probably want to call method that outputs those three messages about emergency. To do that you can do two things:
Create an object of type
emergencyButtonToggled
and call method on that objectemergencyButtonToggled text = new emergencyButtonToggled(); text.main(null);
Add keyword
static
to the method, so you can call it directly on the classemergencyButtonToggled.main(null);
But you shouldn't do any of those things. Instead, it is better to create a static method in emergencyButton
class and call it.
public class emergencyButton {
private static void emergency() {
System.out.println("Buzzer is buzzing");
System.out.println("Emergency, Manual Stop");
System.out.println("Emergency, Water Reservoirs empty");
}
public static void main(String[] args) {
Scanner value = new Scanner(System.in);
System.out.println("Is the emergency button pressed? (Yes/No)");
String button = value.nextLine();
if ("Yes".equals(button)) {
System.out.println("The emergency button is pressed.");
emergency();
} else if ("No".equals(button)) {
System.out.println("Buzzer is not buzzing");
System.out.println("No emergency");
break;
}
}
}
P.S. Function main in your newly created class doesn't have return value, so you should add void
before name of the method (like you can see in my example).