skip to Main Content

I’m trying to run Java in visual studio code but it gives me this error, it works in IntelliJ though

EDIT:
Okay turns out I would need to make a Main.class file inside of the same file of the Main.java file, with that now it works properly in vscode. But I saw a friend of mine just making one new .java file and it works directly, how can I make vscode to be like so?

Main.java:

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

Error:

[Running] cd "/Users/username/Documents/Java Projects/" && javac Main.java && java Main
Main.java:3: error: not a statement
        System
        ^
Main.java:3: error: ';' expected
        System
              ^
2 errors

[Done] exited with code=1 in 0.62 seconds

I tried reinstalling Java in Visual Studio Code to no avail
Update: I think I found the problem: Thing is, I tried out Java first with IntelliJ and before that I’d need to make a Java Project. It works through IntelliJ with that new Project file, when I run said Java program in vscode it works as well, but as soon as I make a new file outside of the project file, or a new file outside of the project folder, it gives out a new error which is this:

Error: Could not find or load main class Main
Caused by: java.lang.ClassNotFoundException: Main

2

Answers


  1. javac main.java && java Main into your visual studio code terminal
    If the error is the same

    then set the temporary environment variable and try javac main.java && java Main again

    Here is my powershell output

    PS C:Usersjilliss> javac Main.java ; java Main
    Hello World
    PS C:Usersjilliss> java -version
    openjdk version "17.0.6" 2023-01-17
    OpenJDK Runtime Environment Temurin-17.0.6+10 (build 17.0.6+10)
    OpenJDK 64-Bit Server VM Temurin-17.0.6+10 (build 17.0.6+10, mixed mode, sharing)
    PS C:Usersjilliss> cat .Main.java
    public class Main {
        public static void main(String[] args) {
            System.out.println("Hello World");
        }
    }
    PS C:Usersjilliss>
    PS C:Usersjilliss> $ENV:JAVA_HOME
    D:winScoopappstemurin17-jdkcurrent
    PS C:Usersjilliss> $ENV:CLASS_PATH
    PS C:Usersjilliss> $ENV:CLASSPATH
    PS C:Usersjilliss>
    

    As you can see, I only set JAVA_HOME but everything works fine, probably because of your jdk version

    Login or Signup to reply.
  2. Do not use Code Runner to execute scripts. Please use the Extension Pack for Java.

    enter image description here

    It will be easier to follow the official documentation to get started.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search