Command Prompt cannot find or run my Java File [duplicate]

元气小坏坏 提交于 2019-12-11 06:38:59

问题


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


来源:https://stackoverflow.com/questions/47266637/command-prompt-cannot-find-or-run-my-java-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!