ChatGPT解决这个技术问题 Extra ChatGPT

Error: Could not find or load main class in intelliJ IDE

I'm a beginner in Java and am trying to run my code using IntelliJ that I just installed as my IDE with JDK 1.7. The following piece of code keeps does not even compile and keeps giving me the error:

Error: Could not find or load main class libTest

Code

import java.lang.Integer;
import java.lang.String;
import java.lang.System;
import java.util.*;

class book {

    private String name = "trial";
    private int bookCode=1;
    private int issued=0;

     public void Issue(){
         if(issued==0) {
             issued=1;
             System.out.println("You have succesfully issued the book");
         }
         else {
             System.out.println("The book is already issued. Please contact the librarian for further details");
         }
    }

    public int checkCode() {
        return bookCode;
    }

    String readName() {
        return name;
    }

    public void setName(String newName){
        name=newName;
    }

    public void setBookCode(int newCode){
        bookCode=newCode;
    }
}

class library {
    private ArrayList books=new ArrayList();

    public void getList(){
        for(int bk:books){
            String bName=books(bk).readName();
            System.out.println((bk+1)+")  "+bName);
        }
    }
}

public class libTest{
    public static void main(String[] args){
        library newLib= new library();
        System.out.println("code working");
   }
}

Is there any change that i have to make in the compiler settings?? Or is it the code.

What's the name of the source file? Is it libTest.java?
import java.lang... This happens automatically for classes in the lang package.
As mentioned by QuantumMechanic, your main class needs to be in a file named exactly like it. So libTest needs to be in a java file named libTest.java, otherwise the java compiler will complain. Also, did you create the source through IDEA, or did you create a new IDEA project over existing source?
tried importing java.lang made no difference
they are identical. Is there any other reason why such a error should get flagged?

K
Kishore

This might help:

1) "Build" menu -> "Rebuild Project". Sometimes Intellij doesn't rewrite the classes because they already exist, this way you ask Intellij to rewrite everything.

2) "Run" menu -> "Edit configuration" -> delete the profile -> add back the profile ("Application" if it's a Java application), choose your main class from the "Main Class" dropdown menu.

3)"Build" menu -> "Rebuild Project".


I had a brand new project in IntelliJ and it would not run. Rebuild Project worked for me!
2nd option worked for me. But delete the configuration profile and then, right click your class --> run
"Build" menu -> "Rebuild Project - did the job! Thanks
The first option rebuild project worked for my problem. Thank you!
I removed the .idea, .mvn and other target directories then restarted IntelliJ. Went to event log , added project as a Maven project and then followed the steps mentioned by @Kishore over here. It is working now.
y
youhans

If none of the above answers worked for you, just close your IntelliJ IDE and remove the IntelliJ IDE file and folder from the root of your project:

rm -rf .idea *.iml 

Then open the project with IntelliJ. It must work now.


This worked for me. I also re-imported my project into IntelliJ, but for the "Group Modules" option, I used "using qualified names" (instead of "using explicit module groups".
Deleting the .idea folder always resolves all the problems with JetBrains' IDEs :)
this worked for me too, I'm a big fan of Intellij, but they must learn to do simple things too.
This worked but i had to set the project settings again.
This fixes almost every problem with IDEA as others have pointed out. My problem was some discrepancies between the actual contents of the project and the .iml file after checking out a branch that is quite old. Since we gitignore .iml files, it sits there and waits while you switch branches, and breaks where you least expected.
U
Uncle Iroh

https://i.stack.imgur.com/RE8gj.png


It's possible that my solution here is actually a subtle variation of @Ehsan's answer below. Perhaps by specifying the target directory it gives it a new location wherein to compile all the objects essentially performing the same work that a Rebuild Project does.
@UncleIroh If it did the same work, rebuilding + reading the config. would have fixed the issue initially. It didn't, but your solution did.
S
Sarah Cohen

I had this problem and I tried everything under the sun that I could think of and on this site.

None of my Java classes were being picked up after I pulled from a remote branch. All the classes had red Js by their names in the Project Hierarchy, not blue Cs.

In the end, I tried to follow this tutorial and a few steps in tried something not described and fixed the issue: https://www.jetbrains.com/help/idea/creating-and-managing-modules.html

Here's what I did:

Goto File | Project Structure, or press Crtl+Shift+Alt+S Select Modules under the Project Settings section. In the Sources tab click Sources on the 'Mark as:' line. Click the Apply button.

For some reason, all my classes then had blue C's.

Someone with a better understanding of how IntelliJ and/or IDE's might be able to explain the phenomenon, but all I know is now it can see all the classes and more importantly the main one, and run.


This only worked for me after I closed Intellij, removed the .idea folder then reopened Intellij and follow the steps above.
B
Brad Turek

Invalidate cache and restart your IntelliJ, it worked for me.

https://i.stack.imgur.com/Twezi.png


B
Brad Turek

Explicitly creating an out folder and then setting the output path to C:\Users\USERNAME\IdeaProjects\PROJECTNAME\out

https://i.stack.imgur.com/ymJNY.png

seemed to work for me when just out, and expecting IntelliJ to make the folder wouldn't.

Also try having IntelliJ make you a new run configuration:

Find the previous one by clicking

https://i.stack.imgur.com/wuxkq.png

then remove it

https://i.stack.imgur.com/Sv89T.png

and hit okay.

Now, (IMPORTANT STEP) open the class containing your main method. This is probably easiest done by clicking on the class name in the left-hand side Project Pane.

Give 'er a Alt + Shift + F10 and you should get a

https://i.stack.imgur.com/mlEAZ.png

Now hit Enter!!

Tadah?? (Did it work?)


The run configuration thing works, especially if you moved the main() function from the class Main to some other class. In that case, edit the run config as shown above and change the value of 'Main class' to your class name(fully qualified).
I have only "Edit configuration" option, doesn't work for me (
S
Sumit Jadiya

https://i.stack.imgur.com/mgrTZ.png


Duplicate answer.
m
msoltys

I know this was asked a while ago, but I was just stumbling over this issue and thought my findings might help others. As pointed out, the error message is basically a result of the out folder. That's because, when you're trying to run the program, it compiles the code first, and puts the compiled result to the out location, and then it tries to load the compiled code from the out location. If the compiled code is not in the location expected, you'll get the error.

The point I'm particularly wanting to share is that some times, the code is not compiled (built), even though your run configuration specifies "Build" in the "Before launch" section of the configuration panel.

When can this happen? One situation that can cause this to happen is if you're using modules and you manually delete the module out directory. For example, if I have a module named "foo", there should be a directory named foo under out/production. If you manually delete it, the build system may not know that it needs to be rebuilt.

Even worse, if you select Build | Build module 'foo', it still may not rebuild the module. If that's the case, you should select a file in the module, for example 'bar.java' and then select Build | Recompile 'bar.java'. Now the out directory out/production/foo should be restored.

Since IntelliJ typically knows about any changes going on, this surprised me, and took me a little time to figure out, so I thought I'd share.


A
Abdessattar NOISSI

Check your class module : I have encountered this problem with intellij : I have a maven multi-module project, the problem is that i runing a class which not exist the module within the configuration, so my problem is fixed by setting the right module ("edit configuration" -> "use class of module")

may this help you


Worked for me too. Thanks! Something had probably gone wrong when installing an upgrade of IntelliJ or the Scala plugin. Afterwards you get this strange problem. Very annoying and time consuming. Hopefully JetBrains finds a resolution.
This worked for me, but the option is now called "Inherit project compile output path".
N
No-Name Nemesis

I had to mark the "src" folder as "Sources". After restarting IntelliJ and rebuilding the project I could run the project without further issues (see screenshot). Edit: You can access the "Project Structure" tab via File->Project Structure or by pressing Ctrl+Shift+Alt+S.


If you (like me) don't have a 'sources' tab, then you should add a new module (click the green +) and select your main folder as the source. Nothing will be overwritten, and the src folder will turn blue.
T
Taras Melnyk

https://i.stack.imgur.com/Ru6qF.png


H
Hakan Serce

I have faced such problems when the class is in the default folder, i.e. when the class does not declare a package.

So I guess using a package statement (eg. package org.me.mypackage;) on top of the class should fix it.


do i replicate that line of code??..how do i modify it in case i have to??
Just use a package name of your own, like this : package org.confused.mailman;
Well, the package statement has to match where the IDE has put the file. If the IDE didn't put the file in sourceBase/org/confused/mailman then adding that package line isn't going to help.
I guess IDE will guide on this, and automatically fix this, if the recommended fix is selected.
not helping :/..the IDE does not seem to be bothered with any of the changes i make..it throws the above error and sits backs and relaxes
l
lleiou

After creating your project in intelliJ, try running the following command:

mvn package

B
Big Pumpkin

I ran into this problem when my Java class was under src/main/kotlin. After I moved it to src/main/java, the problem was gone.


P
Pierluigi Vernetto

I have tried all the hacks suggested here - to no avail. At the end I have simply created a new Maven application and manually copied into it - one by one - the pom.xml and the java files and resources. It all works now. I am new to IntelliJ and totally unimpressed but how easy it is to get it into an unstable state.


You need to close intellij, delete the .idea folder (probably a hidden file); then open the folder again in intellij - it will reinitialize the intelli project based off of the maven / grade config.
b
blindcant

In my case the problem seemed to be related to upgrading IntelliJ. When I did this I overwrote the files from the old IntelliJ with the files from the new IntelliJ (2017 community to 2018 community). After that all of my projects were broken. I tried everything in this thread and none of them worked. I tried upgrading gradle to the latest version (4 to 4.8) and that didn't work. The only thing that worked for me was deleting the entire IntelliJ folder and reinstalling it. All of my projects worked after that.


It seems this actually it. I use portable intellij so I renamed the main folder like from idea\bin to be idea_old\bin and renamed the settings folder in %user%\username which is .IntelliJIdea2018.2 to be .IntelliJIdea2018.2_old then re-extracted intellij zip file to start using it as fresh new portable version (This is version 2018.2.1) with Spring Boot app of multiple separated modules (not linked in single parent pom.xml) each is spring boot app with its own pom.xml and voila !!! All works, target folder created, compiling before running through spring boot dashboard.
S
Smile

Invalidating cache didn't work.

I edited the main class java file with a dummy change and ran it. It worked.


this worked, simple fix
S
Shyam

Goto File-> Invalidate Caches and Restart . Else delete rm -rf .idea *.iml and restart InteliJ


J
JavaTec

For me - i tried few of the options above, did not work. Then i just renamed my Application class and that probably forced intelliJ to build a fresh jar and error message started to change. Then i renamed it back and it worked.


k
kgui

Mark the directory as a source directory. Opened via Ctrl+Shift+Alt+S

https://i.stack.imgur.com/Y4mw1.png


Duplicate answer.
i
ibamboo

https://i.stack.imgur.com/eBPH7.png

modules.xml with wrong content, I don't know what's matter with my IDEA.


c
codeMonkey

I inherited a bunch of .JAVA files from elsewhere and couldn't figure out how to get them to work in any IDE. Ultimately I had to go to the command line where the Main.JAVA file was and run javac Main.java. This created a bunch of .CLASS files. The IDE's were then able to figure out what to do.


B
Beni Murza

I got this error when using Scala/SBT. IntelliJ could not find the main class, even though everything was set up correctly. My solution: delete the <user>/.sbt/<version>/plugins/target folder, then restart IntelliJ.


A
Akash Yellappa

You probably would have specified a wrong package and the package hierarchy would not be right. Look below

https://i.stack.imgur.com/SDcSo.png

The ide would highlight the wrong path in that case.


O
OHY

I'm using IntelliJ with Spring and my main class is wrapped in a JAR. I had to mark the 'Include dependencies with "Provided" scope' in the Run/Debug configuration dialog


K
Kurskinen

We are at File/Project Structure.. Answer might be:

Folder indicated as "content root" needs a child folder where the code is. Plus find the button that marks code as excluded and not. Not to be confused with tickbox that states excluded without telling in what phase and what** Is it compiler exclude or runtime exclude? You are doomed to test and lot. So no that tickbox but icons and colors.

As an idea we need to crack how it was originally thought to work. They never got it to work in first place and started add things in premature codaculation style. It has been so many years and you cannot expect any improvement. But as cure we can hack out some way to get it right every time.


Y
Yep

Another thing you can check here is the actual command that is being passed to the JVM and make sure it looks OK. Scroll to the top of your Run console, it should be the first line.

Spaces in your Run Configuration VM Options field will malform the app startup command and can result in this error message

-DsomeArgument="arg with space must be quoted"

l
lostperson

I have tried almost everything suggested in the answers here, but nothing worked for me.

After an hour of just trying to run my application, I noticed that my project's path included non-ASCII characters (Arabic characters). After I moved my project to a path with no non-ASCII characters, it executed just fine.


s
steven smith

I am working with Kotlin but am guessing the problem is the same. I would start a project, create a single file and add main to it and the IDE couldn't find the main. I tried the things in this list and none worked. I finally mentioned my frustration on one of the IntelliJ pages and was contacted. Of course, it worked fine for IntelliJ. After a couple of days back and forth, I noticed that the highlight function wasn't working and mentioned that. It turned out something was wrong with the IDE settings. I still don't know specifically what was wrong but the fix in my case was to reset the IDE settings. File->Manage IDE Settings->Restore Default settings. After this, the green triangle start icon became visible to the left of my main function and things continued to work normally for subsequent projects. Thanks to Konstantin at JetBrain's support for his patience.


V
Vijay

choose maven as the type while creating project (do not check create from archetype checkbox) Inside Project explorer, right click on java under main under src choose new class complete the class with public static void main choose run from run menu

https://i.stack.imgur.com/kG0Wq.png