-1

I have some problems with Visual Studio Code. I am using the Code Runner extension and Java for Multithreading and Multiprocessing training... but VS Code won't run my code.

Important: The name of the file is Main.java , the same of the public class Main

import java.util.*;


public class Main{
    public static void main(String [] args) {
        PrintThread t = new PrintThread("thread1");
        t.start();
    }
}

class PrintThread extends Thread {
    private int sleepTime;

    public PrintThread(String name) {
        super(name);
        sleepTime = (int) (Math.random() * 5001);
    }

    public void run() {
        try {
            System.err.println(getName() + " going to sleep for " + sleepTime + ".");
            Thread.sleep(sleepTime);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }

        System.err.println(getName() + " done sleeping.");
    }
}

This is the output:

tempCodeRunnerFile.java:5: error: class Main is public, should be
declared in a file named Main.java public class Main{
       ^ 1 error

I tried to change different names of file and public class (same name) but it doesn't work...

starball
  • 20,030
  • 7
  • 43
  • 238
VuciuS
  • 11
  • 1
  • 1
    Looks like the name of the file is not Main.java. With uppercase M. – Jens Apr 23 '23 at 16:38
  • 2
    looks more like it is `tempCodeRunnerFile.java` from the error message `tempCodeRunnerFile.java:5: error: class Main is public, ...` – user16320675 Apr 23 '23 at 16:45
  • 1
    Does this answer your question? [How to avoid tempCodeRunnerFile.go appear in the project](https://stackoverflow.com/questions/63097653/how-to-avoid-tempcoderunnerfile-go-appear-in-the-project) – aled Apr 23 '23 at 16:55
  • I disagree with [the proposed dup target](/q/63097653). I've edited the question to be more clear about what the problem is, and you can see my answer, which should also indicate that the proposed dup target is incorrect. – starball Apr 23 '23 at 23:27

1 Answers1

0

It appears that you're running a selected code snippet. If you want to do that with the Code Runner extension, you'll need to adjust the code-runner.temporaryFileName setting to the name of your main class.

The setting's description:

Temporary file name used in running selected code snippet. When it is set as empty, the file name will be random.

Try editing your workspace .vscode/settings.json file to include the following:

"code-runner.temporaryFileName": "Main"

See also the configuration docs for the Code Runner extension.

If you don't want to run the selected snippet, then make sure you don't have any selected text when invoking Code Runner- either that, or put "code-runner.ignoreSelection": true in your settings.json.

starball
  • 20,030
  • 7
  • 43
  • 238