"Main method not found" error when starting program? [duplicate] - java

This question already has answers here:
"Error: Main method not found in class MyClass, please define the main method as..."
(10 answers)
Closed 4 years ago.
I'm learning Java for my course and I've hit a brick wall. I've been tasked with developing a simple command line program. To make things easier I was given the following sample code to modify so I wouldn't have to start from scratch.
package assignment;
public class Main {
private final static String[] mainMenuOpts = {"Students","Lecturers","Admin","Exit"};
private final static String[] studentMenuOpts = {"Add Student","List all Students","Find a Student","Return to Main Menu"};
private Menu mainMenu = new Menu("MAIN MENU",mainMenuOpts);
private Menu studentMenu = new Menu("STUDENT MENU",studentMenuOpts);
private DataStore data = new DataStore();
private java.io.PrintStream out = System.out;
private ReadKb reader = new ReadKb();
/** Creates a new instance of Main */
public Main() {
run();
}
private void run(){
int ret = mainMenu.display();
while(true){
switch(ret){
case 1: students();break;
case 2: lecturers(); break;
case 3: admin(); break;
case 4: exit(); break;
}
ret = mainMenu.display();
}
}
private void students(){
int ret = studentMenu.display();
while(ret != 4){
switch(ret){
case 1: addStudent();break;
case 2: listStudents(); break;
case 3: findStudent(); break;
}
ret = studentMenu.display();
}
}
private void lecturers(){
out.println("\nLecturers not yet implemented");
}
private void admin(){
out.println("\nAdmin not yet implemented");
}
//Student methods
private void addStudent(){
out.println("\n\tAdd New Student");
//prompt for details
//add student to the datastore
//ask if they want to enter another student -
// if so call addStudent again
//otherwise the method completes and the studentMenu will display again
}
private void listStudents(){
out.println("\n\tStudent Listing");
//list all students from the datastore
}
private void findStudent(){
out.println("\n\tFind Student");
out.print("Enter Search String: ");
//reasd search text
//use datastore method to get list of students that contain the search string
//display matching students
}
// end Student methods
private void exit() {
data.save(); //call the datastore method that will save to file
out.println("\n\nGoodbye :)");
System.exit(0);
}
}
I'm using NetBeans and when I try to run the project I get this error:
Error: Main method not found in class assignment.Main, please define the main method as: public static void main(String[] args)
I just want to get the program running so I can understand the code better. I understand the error, but have no idea where to implement the main method in this wall of text. I've been experimenting for hours, but obviously as a newbie I'm completely useless. Any help would be greatly appreciated.

What you have currently is just a constructor named Main, what Java needs is a main method with exact signature as:
public static void main(String[] args)
public - so that it can be called from outside
static - so that no need to create an instance of your class
void - not going to return any value
args - an array for command line parameters that you can specify while running the program
This is the entry point for your application.
When your current code is being invoked, JVM is trying to locate main method, and since its not present in your code, it's throwing the exception which you have received.
Since you have mentioned beginner in your post, its worth mentioning that Java is a case sensitive language - main and Main are not same in Java.
See also: The getting started tutorial.

The correct signature of main is:
public static void main(String[] args) {
new Main();
}
It's even written in the error message you posted.
Remove the ; from the constructor:
public Main() {
run();
}

You have to use main() method in your program.
From here the program execution starts.
like
public static void main(String args[])
{
//This is the starting point of your program.
}
This method must appear within a class, but it can be any class.
In the Java language, when you execute a class with the Java interpreter, the runtime system starts by calling the class's main() method. The main() method then calls all the other methods required to run your application.
The main() method accepts a single parameter: an array of Strings. This parameter is the mechanism through which the runtime system passes command line arguments to your application

It's looking for a method with this signature:
public static void main(String[] args)
To run your code, the main method can look like this:
public static void main(String[] args)
{
new Main();
}

As the rather helpful error message states, you need a main method. See the java tutorials.

main method should exist for your application to run. Java applications need it to know where to begin executing the program.
Put the method in a class of your choice, and then right click file and select 'Run file`.
public static void main(String[] args)
{
// your code here
}

You need add a main method in your main class so that JVM will know where to start from and not a class with a "main" name.
public static void main(String[] args) {
new Main();
}

Related

Using a instance of a method

I was wondering if someone could help explain how to call a instance of a class.
For example originally I had a file called "Driver"
Then it has a main method that has all the instances needed for a file to run.
Then in that main file it access another file called with a "Games".
So when I run the program "Driver" which has the following code:
import java.util.*;
public class Driver
{
public static void main (String[] args)
{
GameRunner roul = new GameRunner ();
}
}
Then to call an instance of that other file I have something like. Also to make the code work I should have the main method like:
import java.util.*;
public class Driver
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int number = 3;
int userChoice = 0;
GameRunner roul = new GameRunner ();
}
}
Then my other file has something like:
import java.util.*;
class GameRunner
{
public static void roul(Scanner in, int number, int userChoice)
{
Guessing this is still wrong because the driver class should only have :
GameRunner roul = new GameRunner ();
I know it's kinda hard to explain what I'm asking. I hope someone understands.
Thanks.
I strongly recommend reading this (official) tutorial from the people who made Java: https://docs.oracle.com/javase/tutorial/java/concepts/index.html
(No, seriously. Read that tutorial. I linked to the section specifically on object-oriented programming, which explains what you are asking about. It's very useful).
Now to answer your question more directly.
Your roul method is a "class method" (rather than an "instance method") because it has the keyword static in front of its definition. This means that you invoke it using the name of the class, rather than by using a specific object (instance) that you created.
So in order to call the roul method of GameRunner, do the following in your main:
GameRunner.roul(in, number, userChoice);
It is not necessary to instantiate GameRunner unless it has a non-static method that you need to invoke. So unless that's the case, don't do the following:
GameRunner roul = new GameRunner ();
Finally, note that the names of your arguments do not have to be the same as the names of your parameters, as long as their types are the same. The "parameters" are the variables you used when you defined the method. The "arguments" the actual variables you pass to the method.
For example, a method definition has parameters:
public static void myMethod(int parameter1, int parameter2) {
/* do stuff */
}
Whereas a method invocation has arguments that can have a different name:
MyClass.myMethod(number1, number2);
public class Driver {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int number = 3;
int userChoice = 0;
GameRunner runner = new GameRunner ();
// The following line will invoke the target method of your game runner instance.
runner.roul(in, number, userChoice);
}
}
Declare the class and method static then call like this:
GameRunner.roul(); // pass in arguments if needed
public static void run() is the entry point into your application you don't need another one. it looks like you need to brush up on Object Oriented basics.
if you're trying to make a game perhaps you could start with a tutorial? i would suggest using a game library like Lightweight Java Game Library. go ahead and google for some tutorials.

Access one class's members after running it from another class

I recently wrote a class that implements the run method and then parses a video file while grabbing meaningful information. Now I've created a new class that performs a similar operation on the same file but uses a different method of parsing while grabbing other meaningful information. Long story short, I'm required to use two different methods of parsing because some data cannot be extracted by one and some cannot be extracted by the other. The problem I'm facing is that both classes implement the run method, but now I need to start the new class, grab information, start the other class, grab information, then compare the information and print it to the console. This is the gist of what I'm trying to do:
public class first {
[public member variables]
....
public void run(String[] args) {
// parse the file from args and store data
}
public static void main(String[] args) {
new first().run(args); // <------ A
}
}
public class second {
[public member variables]
....
public void run(String[] args) {
// parse the file from args and store data
}
public static void main(String[] args) {
new second().run(args);
}
}
What I'm trying to do is call the first class's main method in order to keep a reference to the class and grab the data from it when it's finished. So I added something like this in the second class:
public class second {
[public member variables]
first firstClass;
int dataFromFirst = 0;
....
public void run(String[] args) {
// parse the file from args and store data
firstClass = new first();
firstClass.main(args); // <------ B
dataFromFirst = firstClass.getSomeData(); // <------ C
}
public static void main(String[] args) {
new second().run(args);
}
}
When I start the second class, everything runs fine, the parser does it's job with both the second and first classes, but when I try to extract the data found by the first class, it's null. I figure once the first class's main method finishes after 'B', once 'A' goes out of scope, everything from the first class is lost. So when I try to get data at 'C', there's nothing there. If this is the case, is there any way I can access the first class's data before it's lost?
I don't have as much knowledge about multithreaded programs so this may just be a very simple solution that I've never seen before.
The reason this doesn't work is that each main method creates its own instance of the class and uses it locally. This has nothing to do with threads, and in fact as far as I can tell your program doesn't actually use multithreading at all.
To fix it, don't call from one main method to the other. In fact, don't even have two main methods in the first place, there's almost never a reason to have more than one. Instead, simply call run directly, like this:
public void run(String[] args) {
// parse the file from args and store data
firstClass = new first();
firstClass.run(args);
dataFromFirst = firstClass.getSomeData();
}

Main method not found in class Television, please define the main method as:public static void main(String[] args)

This program must print final parametres about a TV state in three (3) rows...
in first row...on which level loudness is...
in the second on which program is (1., 2., 56, etc...)
third row - is it turned on...
(after all operations inside programm)... this programm is pasted from manual for Java...
class Television {
int volumeTone = 0;
int channelNow = 1;
boolean turnedOn = false;
void turnOn(){
turnedOn = true;
}
void turnOff(){
turnedOn = false;
}
void increaseVolume(){
volumeTone = volumeTone + 1;
}
void decreaseVolume(){
volumeTone = volumeTone - 1;
}
void turnOffVolume(){
volumeTone = 0;
}
void changeChannelUp(){
channelNow = channelNow + 1;
}
void changeChannelDown(){
channelNow = channelNow - 1;
}
int returnChannelBefore(){
return channelNow;
}
int returnToneVolume(){
return volumeTone;
}
boolean isItTurnedOn(){
return turnedOn;
}
void writeParametres(){
System.out.println("Volume loudness now is "+volumeTone);
System.out.println("Channel now is "+channelNow);
System.out.println("Tv is turned on? "+turnedOn);
}
}
You need to have a main method in the class to run...
Your exception itself say that, please define the main method as:public static void main(String[] args)
You need main method in your class Television as shown below.
public static void main(String[] args)
{
//Your logic run this class
}
In Java, you need to have a method named main in at least one class.
Please refer this link about main method.
Without a main method, you will not be able to run anything. Create a new class with a main method like so:
public class myClass
{
public static void main(String [] args)
{
//Here you can create an instance of your television class
Television tel = new Television();
//You can then call methods on your newly created instance
tel.turnOn();
}
}
The main entrance to a java application is with a static main method
which is usually defined as;
public static void main(String []args)
{
}
If you want to run any class make sure it has this method.
You will need to Implement main method
From The Java Tutorials' Hello World Example: (emphasis mine)
In the Java programming language, every application must contain a main method whose signature is: public static void main(String[] args)
...
The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.
In other words, when running a Java class, the JVM will look for a main() method in it. That method will be called automatically when running the class, and will be the entry point for the execution flow of the program.
Also, take a look at How does the main method work?.

"Main method not found" error - what is missing in this code? [duplicate]

This question already has answers here:
"Main method not found" error when starting program? [duplicate]
(7 answers)
Closed 9 years ago.
I was just re-reading my lecture scripts and trying out the code there. The problem is that the professor gave us only fragments of code and I really stuck on this one. I keep getting this error in Eclipse:
no main method
I still get the error even if I put public static void main(String[] args) in the code. What should I change in it?
The main idea of this program is to calculate a square or square root.
public class MeineKlasse {
private String job;
private String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
System.out.println(job);
}
public double myMethode(double x) throws Exception {
if (job.equals("quadrat"))
return x * x;
if (job.equals("wurzel"))
return Math.sqrt(x);
System.out.println(myMethode(x) + "=");
throw new Exception("Fehler:Aufgabe nicht korrekt definiert");
}
}
Every program needs entry point. The entry point to any java program is
public static void main(String[] args)
You have to implement this method. It will run the rest of your application.
If you get error like no main method it means you had to put your main method in the incorrect place. Make sure also your curly brackets are closed and follow this structure
public static MeineKlasse {
public static void main(String[] args) {
//your code
//...
//...
//...
}
}
What AlexR said is correct. Every program needs a main method, which is what runs the program.
You can fix it with something like this:
public class MeineKlasse {
private String job;
public static void main(String[] args) { //main method
MeineKlasse meineKlasse = new MeineKlasse();
meineKlasse.setJob("quadrat");
System.out.println(meineKlasse.myMethode(3.6));
} //end main method
private String getJob() {
return job;
}
.
.
.
}
Another problem you have is in myMethode(double x).
public double myMethode(double x) throws Exception {
if (job.equals("quadrat"))
return x * x;
if (job.equals("wurzel"))
return Math.sqrt(x);
System.out.println(myMethode(x) + "="); //this line
throw new Exception("Fehler:Aufgabe nicht korrekt definiert");
}
On line 6, the method calls itself. When it calls itself, it repeats the method over again, including calling itself. Because it just called itself again, it will go through the code until it calls itself, etc. This results in a StackOverflowException, because the method would otherwise repeat itself forever. To fix this, you can just remove the line, as the program already prints the result in the main method.

How to execute a particular function before main() in C and JAVA ?

I want to execute one function before main function in C and JAVA language.
I know one way that is, by using #pragma directive in C language. Is there any other way to do that in both languages?
I can think of two simple(-ish) ways to do it in Java:
Method #1 - static initializers
For example:
public class Test {
static {
System.err.println("Static initializer first");
}
public static void main(String[] args) {
System.err.println("In main");
}
}
Method #2 - A proxy main.
public class ProxyMain {
public static void main(String[] args) {
String classname = args[0];
// Do some other stuff.
// Load the class
// Reflectively find the 'public static void main(String[])' method
// Reflectively invoke it with the rest of the args.
}
}
You then launch this as:
java <jvm-options> ... ProxyMain <real-Main> arg ...
There is also a 3rd method, but it requires some "extreme measures". Basically you have to create your own JVM launcher that uses a different scheme for starting the application. Have this do the extra stuff before loading the entry point class and calling its main method. (Or do something different entirely.)
You could even replace the default classloader; e.g. How to change default class loader in Java?
in java you can use static block
public class JavaApplication2 {
static {
System.out.println("in static ");
}
public static void main(String[] args) {
System.out.println("in main ");
}
}
As an extension to the C standard gcc provides the function attribute constructor which allows functions to be called before main().
For details please see here (scroll down). Also this SO question and its answers help on this.
Try combining a static block and a static method containing what you want executed before your main method.
package test;
public class Main {
static {
beforeMain();
}
public static void main(String[] args) {
System.out.println("after");
}
private static void beforeMain() {
System.out.println("before");
}
}
Output:
before
after
It could be the first thing you call from your main function. That way it will run before your "real" main function.
Use that method(what you want to run before main method) as your main method.
Then it is so simple
Or use static block before main()
In java, execution of any other method is possible before main() method execution. We need a static initializer block for that. It starts with a static keyword.
Like:
static {
// statements
}
Now try to understand with actual code implementation.
public class BefourMain {
static int sum;
static {
sum = add(4,5,6);
System.out.println("Calling add() method: " + sum);
System.out.println("\ncalling main");
main(null);
System.out.println("Main end\n");
System.out.println("Now JVM calling main()\n");
}
public static void main(String[] args) {
int sum = add(1,2,3);
System.out.println(sum);
}
static int add(int a, int b, int c) {
return a + b + c;
}
}
Now try to understand with actual code implementation.
When we start executing this code the static initializer block will start execution first, in the static initializer block we are calling the add() method and storing the value in the static variable, and printing it. Next, we are calling the main() method, which will execute. when the static initializer block execution will complete JVM will call the main() method again.
Output
Output of the above code

Categories

Resources