Command Prompt cannot find or run my Java File [du

2019-08-15 00:10发布

问题:

This question already has an answer here:

  • How do I run a Java program from the command line on Windows? 12 answers

New programmer here, in terms of actually using an editor and running it. I have created a simple program that states this.

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }
}

I have already set the path to "C:\Program Files\Java\jdk1.8.0_151\bin\".(current version"1.8.0_151"). In the cmd input, "java" and "javac" work until I attempt to find a file name either "HelloWorld.java" or "HelloWorld". How do I get cmd to find and run my java file? Thank you!

回答1:

One way to try it:

Open C:\Temp (or create if not exists)

Create new file called HelloWorld.java

Open cmd

Type cd /d C:\Temp

Type javac HelloWorld.java

Type java HelloWorld



回答2:

I did the following steps with your code and it worked:

  • Open a command prompt in the folder where your HelloWorld.java is saved
  • Make sure the class name is the same as the file name.
  • Check if you have added java executable/folder to your system path, you can try: java -version (this should print information about your installed java version)
  • Compile your code: javac HelloWorld.java
  • Now there should be a class file generated: HelloWorld.class
  • Run you main class: java HelloWorld
  • Note: Without the .class extenstion
  • Note: use dir instead of ls on Windows to see the files in the current directory
  • Note: Do you have a package name specified?



回答3:

you compile with javac eg:

javac HelloWorld.java

you run the compiled byte code using java. You need to place yourself in the directory containing the compiled bytecode eg

C:\introcs\hello\>java HelloWorld
Hello, World


标签: java cmd javac