cmd java not working [duplicate]

拜拜、爱过 提交于 2019-12-02 12:31:20

The name of my class is Hello so I typed javac Hello.java to compile my file as a class file and it worked. But when I enter: java Hello

The most likely problem is that while running your java program you are not putting the complete class name along with the package structure. It should be run as mentioned here:

java packagenhierarchy.Hello 

Assuming your package name is com.my.hello and your main class name is Hello then it should be run from the directory containing the top level package as:

java com.my.hello.Hello

UPDATE: As per your comments and knowing the working directory, here is what you should run:

java -cp C:\hello\src\hello hello.Hello

You need to understand how java tool works which is little different than how javac works. In order to run a program with java command-line command:

  1. The class that has the main(String[] args) method should be in the classpath.
  2. Instead of type java Hello you should use the fully qualified name, such as:
java com.mypackage.Hello

assuming that you set the classpath with the variable CLASSPATH. Otherwise, it should be like this:

java -cp C:\projects\myprojct\bin com.mypackage.Hello

assuming that bin is the root directory that has the following hierarchy:

bin -
     |
     com -
         |
         mypackage -
                   |
                   Hello.class

Note that if you don't use neither CLASSPATH nor -cp nor -classpath, then the current directory is by default is in the classpath. In other words, the following should work:

cd C:\projects\myprojct\bin
java com.mypackage.Hello

Maybe your current directory is not in the Class path. Try

java -cp pathToYourHelloCompiledFile Hello

You must have a Hello.class file in your above folder whose path you provide as the class path.

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