Static void main string args выдает ошибку

Afaq

1 / 1 / 0

Регистрация: 20.07.2014

Сообщений: 70

1

26.08.2014, 01:06. Показов 6103. Ответов 6

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

почему метод static void Main дает ошибку? помогите

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    class Program
    {
        
       private static void MassivMinElement(int [] b)
        {
            
            int min = b[0];
            for (int i = 0; i < b.Length; i++)
            {
 
                if (min > b[i])
                {
                    min = b[i];
                }
 
            }
            Console.WriteLine(min);
       }
 
            private static void MassivMaxElementi(int [] a)
        {
            
            int max = a[0];
            for (int i = 0; i < a.Length; i++)
            {
 
                if (max < a[i])
                {
                    max = a[i];
                }
 
            }
            Console.WriteLine(max);
 
        }
 
        }
 
        static void Main(string[] args)
        {
  
        }
    }
}



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

26.08.2014, 01:06

Ответы с готовыми решениями:

static void Main(string[] args)
Что такое string args
в строке static void Main(string args)
и зачем это писать, если void,…

Перегрузите метод f так, чтобы соответствовала виду static void f (double x, out double y)
ПОМОГИТЕ!! Выдаёт ошибку!
До передачи управления из текущего метода выходному параметру &quot;y&quot; должно…

Перегрузите метод f так, чтобы его сигнатура соответствовала виду static void f (double x, out double y)
Как сделать метод, чтобы он соответствовал заданию?

class Program
{
static double…

Перегрузите метод f так, чтобы его сигнатура (заголовок) соответствовала виду static void f (double x, out double y)
Перегрузите метод f так, чтобы его сигнатура (заголовок) соответствовала виду static void f (double…

6

64 / 63 / 43

Регистрация: 01.05.2012

Сообщений: 535

26.08.2014, 01:15

2

А что вы вообще хотите? Какая именно ошибка?
В первую очередь выполняется Main, из него уже нужно вызывать MassivMinElement и MassivMaxElementi.



0



1 / 1 / 0

Регистрация: 20.07.2014

Сообщений: 70

26.08.2014, 01:21

 [ТС]

3

awp-sirius, у меня вообще метод static void main не работает, всегда дает 11 ошибок.



0



Butter

Заблокирован

26.08.2014, 01:23

4

Не может он чистый давать ошибки значит чтото правилось еще вылаживайте весь код постараюсь помочь



1



Afaq

1 / 1 / 0

Регистрация: 20.07.2014

Сообщений: 70

26.08.2014, 01:28

 [ТС]

5

awp-sirius, примерно что то такое хочу написать такое:

C#
1
2
3
4
5
6
7
int[] massiv = new int[5];
            Random rd = new Random();
            for (int i = 0; i < 5; i++)
            {
                massiv[i] = rd.Next(1, 9);
            }
            MassivMaxElement(massiv);

Добавлено через 4 минуты
Butter, odin metod doljen vozvrashat znaceniye Max, druqoy minimum.



0



Butter

Заблокирован

26.08.2014, 01:32

6

Лучший ответ Сообщение было отмечено Afaq как решение

Решение

Для начала у вас в коде в 1 посте слишком рано закрывается скобка класса.
В коде ниже вы вызываете не ту функцию вы вызываете MassivMaxElement а у вас MassivMaxElementi

Добавлено через 1 минуту

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private void MassivMaxElementi(int [] a)
        {
            
            int max = a[0];
            for (int i = 0; i < a.Length; i++)
            {
 
                if (max < a[i])
                {
                    max = a[i];
                }
 
            }
            Console.WriteLine(max.ToString());
 
        }
 static void Main(string[] args)
        {
             int[] massiv = new int[5];
            Random rd = new Random();
            for (int i = 0; i < 5; i++)
            {
                massiv[i] = rd.Next(1, 9);
            }
 
            MassivMaxElementi(massiv);
        }



1



1 / 1 / 0

Регистрация: 20.07.2014

Сообщений: 70

26.08.2014, 01:36

 [ТС]

7

Butter, spasibo!



0



I want to create a simple java class, with a main method, but when I compile my code, I get this error message :

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

This is the source code :

package errors;

public class TestErrors {
    public static void main(String[] args){
        System.out.println("hello");
    }
}

Why I’m seeing this error, as you can notice I’ve alreader declared the main method !

asked Oct 12, 2013 at 20:51

user2874861's user avatar

8

As said in my comments, looks like you’ve declared a String class among your own classes. To prove this, I’ve created a basic example:

class String {
}

public class CarelessMain {
    public static void main(String[] args) {
        System.out.println("won't get printed");
    }
    public static void main(java.lang.String[] args) {
        System.out.println("worked");
    }
}

If you execute this code, it will print "worked" in the console. If you comment the second main method, the application will throw an error with this message (similar for your environment):

Error: Main method not found in class edu.home.poc.component.CarelessMain, please define the main method as:

public static void main(String[] args)

Community's user avatar

answered Oct 12, 2013 at 20:59

Luiggi Mendoza's user avatar

Luiggi MendozaLuiggi Mendoza

84.9k16 gold badges153 silver badges328 bronze badges

2

This usually happens if ur complete project isnotconfigured correctly
or one of your class in project has still some errors
in such cases IDE will prompt stating the same that project contains some error
and you still proceed (ie run your class)
as project has some bugs new classes will not be created and IDE will run
the class which was available previously

to make sure this is ur case u can add new class in your project and try to run it and if ur getting no such class exist then there its is a perfect evidence

Luiggi Mendoza's user avatar

answered Feb 14, 2014 at 11:28

Prashant's user avatar

PrashantPrashant

811 silver badge3 bronze badges

Just check your java file, it has not been saved. Please save all java files before compiling.

answered Sep 30, 2016 at 19:02

Ashutosh Ranjan's user avatar

2

If the answers above are not working for you: make sure «main» is not capitalized in your method definition.

OK:
public static void main(String[] args)

ERROR:
public static void Main(String[] args)

Though the error message makes the required syntax for the main method clear, incorrect caps can be hard to spot. It took me ~30 minutes of troubleshooting to find this typo today. This was clearly not an issue for the OP, but is another easy/likely way to produce the same error message, and this answer may help other users.

answered Dec 1, 2018 at 20:18

Chris Keefe's user avatar

Chris KeefeChris Keefe

7976 silver badges17 bronze badges

I had this issue just now. This error came up because the JRE file that i switched out didn’t had the full library. After I corrected/added the right JRE system library the problem went away.

answered Mar 11, 2020 at 1:12

curtis Lewis's user avatar

Right click on the class name (which you are trying to run)->Run As->Run Configurations->Under Main Class Tab

Write your main class name and hit on Run.

JJJ's user avatar

JJJ

32.8k20 gold badges89 silver badges102 bronze badges

answered Mar 26, 2017 at 10:50

Vinay Murali's user avatar

Try commenting the first line.

//package errors;

Petter Friberg's user avatar

answered Nov 26, 2017 at 13:18

Hei 's user avatar

The java error: main method not found in the file, please define the main method as: public static void main(string[] args) occurs if the main method not found in class or the main method is not accessible or the main method is invalid. The main method indicates the start of the application. The main method syntax must be as public static void main(String[] args) { }. Alternatively, java program must extend javafx.application.Application. Otherwise, “or a JavaFX application class must extend javafx.application.Application” error will be shown.

In Java, each application must have the main method. The main method is the entry point of every java program. The java program searches for the main method while running. This error occurred when the main method is not available.

In java, the JavaFX application does not to have a main method, instead the JavaFX application must extend javafx.application.Application class. Otherwise “Error: Main method not found in class, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application” exception will be thrown in java.

Exception

Error: Main method not found in class, please define the main method as:
    public static void main(String[] args)
 or a JavaFX application class must extend javafx.application.Application
Error: Main method is not static in class, please define the main method as:
   public static void main(String[] args)
Error: Main method must return a value of type void in class, please 
define the main method as:
   public static void main(String[] args)

Error Code

The Error code looks like as below. If you run javac Test.java & java Test The above exception will be thrown. The Test class neither have main method nor extend javafx.application.Application class.

package com.yawintutor;

public class Test {

}

Root Cause

Spring boot is looking for the main method to start the spring boot application. This error occurred because the main method is not available.

Any one of the following is the possible cause of this issue

  • The main method is deleted
  • The main method name is renamed
  • The signature of the main method is changed
public static void main(String[] args) {
// block of code 		
}

Solution 1

The java main method is the entry point of the java program. If the main method is missing in the program, the exception will be thrown. Check the main method in the code, and add the main method as shown below.

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

The below example shows the main method of the spring boot application.

package com.yawintutor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringHelloWorldApplication {

	public  void main(String[] args) {
		SpringApplication.run(SpringHelloWorldApplication.class, args);
	}

}

Solution 2

The main method in the java application must be public. If it is not a public, java compiler can not access the main method. If the access specifier is not specified or not a public, then the exception will be thrown.

package com.yawintutor;

public class Test {
	static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Output

Error: Main method not found in class com.yawintutor.Test, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Solution 3

If the main method does not have static keyword, the main method can not access from outside of the class. The object of the class only can access the main method. To create a object, the main method must be executed. This will cause the exception.

package com.yawintutor;

public class Test {
	public void main(String[] args) {
		System.out.println("Hello World");
	}
}

Output

Error: Main method is not static in class com.yawintutor.Test, please define the main method as:
   public static void main(String[] args)

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Solution 4

The main method must return void. If the return data type is added other than void. the exception will be thrown.

package com.yawintutor;

public class Test {
	public static int main(String[] args) {
		System.out.println("Hello World");
		return 0;
	}
}

Output

Error: Main method must return a value of type void in class com.yawintutor.Test, please 
define the main method as:
   public static void main(String[] args)

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Solution 5

The main method must have only one argument. The argument must be a string array. If no argument is configured or different data type argument is configured or more than one argument is configured, the exception will be thrown.

package com.yawintutor;

public class Test {
	public static void main() {
		System.out.println("Hello World");
	}
}

Output

Error: Main method not found in class com.yawintutor.Test, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

How to create simple Spring Boot Application with Main method

Afaq

1 / 1 / 0

Регистрация: 20.07.2014

Сообщений: 70

1

26.08.2014, 01:06. Показов 5826. Ответов 6

Метки нет (Все метки)


почему метод static void Main дает ошибку? помогите

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    class Program
    {
        
       private static void MassivMinElement(int [] b)
        {
            
            int min = b[0];
            for (int i = 0; i < b.Length; i++)
            {
 
                if (min > b[i])
                {
                    min = b[i];
                }
 
            }
            Console.WriteLine(min);
       }
 
            private static void MassivMaxElementi(int [] a)
        {
            
            int max = a[0];
            for (int i = 0; i < a.Length; i++)
            {
 
                if (max < a[i])
                {
                    max = a[i];
                }
 
            }
            Console.WriteLine(max);
 
        }
 
        }
 
        static void Main(string[] args)
        {
  
        }
    }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

26.08.2014, 01:06

Ответы с готовыми решениями:

static void Main(string[] args)
Что такое string args
в строке static void Main(string args)
и зачем это писать, если void,…

Перегрузите метод f так, чтобы соответствовала виду static void f (double x, out double y)
ПОМОГИТЕ!! Выдаёт ошибку!
До передачи управления из текущего метода выходному параметру &quot;y&quot; должно…

Перегрузите метод f так, чтобы его сигнатура соответствовала виду static void f (double x, out double y)
Как сделать метод, чтобы он соответствовал заданию?

class Program
{
static double…

Перегрузите метод f так, чтобы его сигнатура (заголовок) соответствовала виду static void f (double x, out double y)
Перегрузите метод f так, чтобы его сигнатура (заголовок) соответствовала виду static void f (double…

6

64 / 63 / 43

Регистрация: 01.05.2012

Сообщений: 535

26.08.2014, 01:15

2

А что вы вообще хотите? Какая именно ошибка?
В первую очередь выполняется Main, из него уже нужно вызывать MassivMinElement и MassivMaxElementi.

0

1 / 1 / 0

Регистрация: 20.07.2014

Сообщений: 70

26.08.2014, 01:21

 [ТС]

3

awp-sirius, у меня вообще метод static void main не работает, всегда дает 11 ошибок.

0

Butter

Заблокирован

26.08.2014, 01:23

4

Не может он чистый давать ошибки значит чтото правилось еще вылаживайте весь код постараюсь помочь

1

Afaq

1 / 1 / 0

Регистрация: 20.07.2014

Сообщений: 70

26.08.2014, 01:28

 [ТС]

5

awp-sirius, примерно что то такое хочу написать такое:

C#
1
2
3
4
5
6
7
int[] massiv = new int[5];
            Random rd = new Random();
            for (int i = 0; i < 5; i++)
            {
                massiv[i] = rd.Next(1, 9);
            }
            MassivMaxElement(massiv);

Добавлено через 4 минуты
Butter, odin metod doljen vozvrashat znaceniye Max, druqoy minimum.

0

Butter

Заблокирован

26.08.2014, 01:32

6

Лучший ответ Сообщение было отмечено Afaq как решение

Решение

Для начала у вас в коде в 1 посте слишком рано закрывается скобка класса.
В коде ниже вы вызываете не ту функцию вы вызываете MassivMaxElement а у вас MassivMaxElementi

Добавлено через 1 минуту

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private void MassivMaxElementi(int [] a)
        {
            
            int max = a[0];
            for (int i = 0; i < a.Length; i++)
            {
 
                if (max < a[i])
                {
                    max = a[i];
                }
 
            }
            Console.WriteLine(max.ToString());
 
        }
 static void Main(string[] args)
        {
             int[] massiv = new int[5];
            Random rd = new Random();
            for (int i = 0; i < 5; i++)
            {
                massiv[i] = rd.Next(1, 9);
            }
 
            MassivMaxElementi(massiv);
        }

1

1 / 1 / 0

Регистрация: 20.07.2014

Сообщений: 70

26.08.2014, 01:36

 [ТС]

7

Butter, spasibo!

0

The java error: main method not found in the file, please define the main method as: public static void main(string[] args) occurs if the main method not found in class or the main method is not accessible or the main method is invalid. The main method indicates the start of the application. The main method syntax must be as public static void main(String[] args) { }. Alternatively, java program must extend javafx.application.Application. Otherwise, “or a JavaFX application class must extend javafx.application.Application” error will be shown.

In Java, each application must have the main method. The main method is the entry point of every java program. The java program searches for the main method while running. This error occurred when the main method is not available.

In java, the JavaFX application does not to have a main method, instead the JavaFX application must extend javafx.application.Application class. Otherwise “Error: Main method not found in class, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application” exception will be thrown in java.

Exception

Error: Main method not found in class, please define the main method as:
    public static void main(String[] args)
 or a JavaFX application class must extend javafx.application.Application
Error: Main method is not static in class, please define the main method as:
   public static void main(String[] args)
Error: Main method must return a value of type void in class, please 
define the main method as:
   public static void main(String[] args)

Error Code

The Error code looks like as below. If you run javac Test.java & java Test The above exception will be thrown. The Test class neither have main method nor extend javafx.application.Application class.

package com.yawintutor;

public class Test {

}

Root Cause

Spring boot is looking for the main method to start the spring boot application. This error occurred because the main method is not available.

Any one of the following is the possible cause of this issue

  • The main method is deleted
  • The main method name is renamed
  • The signature of the main method is changed
public static void main(String[] args) {
// block of code 		
}

Solution 1

The java main method is the entry point of the java program. If the main method is missing in the program, the exception will be thrown. Check the main method in the code, and add the main method as shown below.

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

The below example shows the main method of the spring boot application.

package com.yawintutor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringHelloWorldApplication {

	public  void main(String[] args) {
		SpringApplication.run(SpringHelloWorldApplication.class, args);
	}

}

Solution 2

The main method in the java application must be public. If it is not a public, java compiler can not access the main method. If the access specifier is not specified or not a public, then the exception will be thrown.

package com.yawintutor;

public class Test {
	static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Output

Error: Main method not found in class com.yawintutor.Test, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Solution 3

If the main method does not have static keyword, the main method can not access from outside of the class. The object of the class only can access the main method. To create a object, the main method must be executed. This will cause the exception.

package com.yawintutor;

public class Test {
	public void main(String[] args) {
		System.out.println("Hello World");
	}
}

Output

Error: Main method is not static in class com.yawintutor.Test, please define the main method as:
   public static void main(String[] args)

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Solution 4

The main method must return void. If the return data type is added other than void. the exception will be thrown.

package com.yawintutor;

public class Test {
	public static int main(String[] args) {
		System.out.println("Hello World");
		return 0;
	}
}

Output

Error: Main method must return a value of type void in class com.yawintutor.Test, please 
define the main method as:
   public static void main(String[] args)

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Solution 5

The main method must have only one argument. The argument must be a string array. If no argument is configured or different data type argument is configured or more than one argument is configured, the exception will be thrown.

package com.yawintutor;

public class Test {
	public static void main() {
		System.out.println("Hello World");
	}
}

Output

Error: Main method not found in class com.yawintutor.Test, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

How to create simple Spring Boot Application with Main method

In Java programs, the point from where the program starts its execution or simply the entry point of Java programs is the main() method. Hence, it is one of the most important methods of Java and having a proper understanding of it is very important.

The Java compiler or JVM looks for the main method when it starts executing a Java program. The signature of the main method needs to be in a specific way for the JVM to recognize that method as its entry point. If we change the signature of the method, the program compiles but does not execute.

The execution of the Java program, the java.exe is called. The Java.exe inturn makes Java Native Interface or JNI calls, and they load the JVM. The java.exe parses the command line, generates a new String array, and invokes the main() method. A daemon thread is attached to the main method, and this thread gets destroyed only when the Java program stops execution.

Java main() Method

Syntax: Most common in defining main() method

Java

class GeeksforGeeks {

    public static void main(String[] args)

    {

        System.out.println("I am a Geek");

    }

}

Output explanation:  Every word in the public static void main statement has got a meaning to the JVM. 

1. Public 

It is an Access modifier, which specifies from where and who can access the method. Making the main() method public makes it globally available. It is made public so that JVM can invoke it from outside the class as it is not present in the current class.

Java

class GeeksforGeeks {

    private static void main(String[] args)

    {

        System.out.println("I am a Geek");

    }

}

Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

2. Static

It is a keyword that is when associated with a method, making it a class-related method. The main() method is static so that JVM can invoke it without instantiating the class. This also saves the unnecessary wastage of memory which would have been used by the object declared only for calling the main() method by the JVM.

Java

class GeeksforGeeks {

    public void main(String[] args)

    {

        System.out.println("I am a Geek");

    }

}

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

3. Void 

It is a keyword and is used to specify that a method doesn’t return anything. As the main() method doesn’t return anything, its return type is void. As soon as the main() method terminates, the java program terminates too. Hence, it doesn’t make any sense to return from the main() method as JVM can’t do anything with the return value of it.

Java

class GeeksforGeeks {

    public static int main(String[] args)

    {

        System.out.println("I am a Geek");

        return 1;

    }

}

Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

4. main 

It is the name of the Java main method. It is the identifier that the JVM looks for as the starting point of the java program. It’s not a keyword.

Java

class GeeksforGeeks {

    public static void myMain(String[] args)

    {

        System.out.println("I am a Geek");

    }

}

Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

5. String[] args 

It stores Java command-line arguments and is an array of type java.lang.String class. Here, the name of the String array is args but it is not fixed and the user can use any name in place of it. 

Java

class GeeksforGeeks {

    public static void main(String[] args)

    {

        for (String elem : args)

            System.out.println(elem);

    }

}

Output:

1
2
3 

Apart from the above-mentioned signature of main, you could use public static void main(String args[]) or public static void main(String… args) to call the main function in Java. The main method is called if its formal parameter matches that of an array of Strings.

Can the main method be int? If not, why?

Java

class GeeksforGeeks {

public static int main(String[] args)

    {

        System.out.println("GeeksforGeeks");

    }

}

 
Java does not return int implicitly, even if we declare the return type of main as int. We will get a compile-time error: 

prg1.java:6: error: missing return statement

   }

   ^

1 error

Java

class GeeksforGeeks {

   public static int main(String[] args) {

       System.out.println("GeeksforGeeks");

       return 0;

   }

}

Now, even if we do return 0 or integer explicitly ourselves, from int main. We get a run time error.

Error: Main method must return a value of type void in class GeeksforGeeks, please  
define the main method as:
  public static void main(String[] args)

Explanation: 

The C and C++ programs which return int from main are processes of Operating System. The int value returned from main in C and C++ is exit code or exit status. The exit code of the C or C++ program illustrates, why the program was terminated. Exit code 0 means successful termination. However, the non-zero exit status indicates an error. 

For Example exit code 1 depicts Miscellaneous errors, such as “divide by zero”.

The parent process of any child process keeps waiting for the exit status of the child. And after receiving the exit status of the child, cleans up the child process from the process table and free the resources allocated to it. This is why it becomes mandatory for C and C++ programs(which are processes of OS) to pass their exit status from the main explicitly or implicitly.

However, the Java program runs as a ‘main thread’ in JVM. The Java program is not even a process of Operating System directly. There is no direct interaction between the Java program and Operating System. There is no direct allocation of resources to the Java program directly, or the Java program does not occupy any place in the process table. Whom should it return an exit status to, then? This is why the main method of Java is designed not to return an int or exit status.

But JVM is a process of an operating system, and JVM can be terminated with a certain exit status. With help of java.lang.Runtime.exit(int status) or System.exit(int status).

Can we execute a java program without main method?

Yes, we can execute a java program without a main method by using a static block.

A static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by ClassLoader, It is also known as a static initialization block, and it goes into the stack memory.

class StaticBlock {
    static
    {
        System.out.println(
            "This class can be executed without main");
        System.exit(0);
    }
}

В IDEA компилируется, тут не проходит по 4-му пункту. Почему ?

public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int count = 0;
List<Integer> list = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
for (int i = 0; i < 10; i++)
list.add(Integer.parseInt(reader.readLine()));
list.add(0);
for (int i = 0; i < 10; i++)
if (list.get(i).equals(list.get(i + 1)))
count++;
else {
list1.add(count);
count = 0;
}
System.out.println(Collections.max(list1) + 1);
}
}

package com.javarush.task.task08.task0812;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/*
Cамая длинная последовательность
*/
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int count = 0;
List<Integer> list = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
for (int i = 0; i < 10; i++)
list.add(Integer.parseInt(reader.readLine()));
list.add(0);
for (int i = 0; i < 10; i++)
if (list.get(i).equals(list.get(i + 1)))
count++;
else {
list1.add(count);
count = 0;
}
System.out.println(Collections.max(list1) + 1);
}
}

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

Понравилась статья? Поделить с друзьями:
  • Statement ignored oracle ошибка
  • State of survival ошибка 41001
  • State of survival 110000 ошибка
  • State of decay ошибка при запуске приложения 0xc000007b
  • State of decay ошибка запуска