I did a module in Java in college but we did it all using Eclipse. Now I'd like to go back and learn it but by using the command line.
I set up a folder on my desktop, wrote ou开发者_如何学Ct my application and saved it as 'MyFirstApp.java'. Here it is:
public class MyFirstApp {
public static void main (String[] args) {
System.out.print("Hello World!");
}
}
I opened my command line, cd'd into the appropriate directory and then compiled by typing "javac MyFirstApp.java". This creates a file in the folder called "MyFirstApp.class".
However when I try to run this by typing "java MyFirstApp" I get an error:
Exception in thread "main" java.lang.NoClassDefFoundError: MyFirstApp
Caused by: java.lang.ClassNotFoundException: MyFirstApp
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: Share.class. Program will exit.
I also tried running by typing "java -cp.MyFirstApp" but then I get this error:
Unrecognised option: -cp.MyFirstApp
Could not create the Java Virtual Machine
Is this likely to be a problem with my environmental variables? I don't really know much about all this stuff.
You should add a space between cp and class name:
java -cp . MyFirstApp
Try running it as
java -cp . MyFirstApp
instead. (Note the spaces.)
It's odd though, as normally the current directory is already on the classpath...
This is most likely happening because you do not have the current directory in your CLASSPATH environment variable. It can't find the .class file even though it exists in the directory you are trying to run it from.
You can either add the current directory (which is a single dot ".") to the CLASSPATH environment variable, or you can pass the classpath explicitly by using the -cp argument.
Try setting the classpath to the current folder like this (note the spaces in between):
java -cp . MyFirstApp
Try by setting path and classpath
精彩评论