Link to home
Start Free TrialLog in
Avatar of Vampireofdarkness
VampireofdarknessFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Java beginner - book code not working.. what a way to learn!

class Motorcycle {

      public static void main(String args[]) {
            Motorcycle m=new Motorcycle();
            m.make="Yamaha";
            m.colour="Yellow";
            System.out.println("Calling showAtts");
            m.showAtts();
            System.out.println("----------");
            System.out.println("Starting engine");
            m.startEngine();
            System.out.println("----------");
            System.out.println("Calling showAtts");
            m.showAtts();
            System.out.println("----------");
            System.out.println("Starting engine");
            m.startEngine();
      }

      String make;
      String colour;
      boolean engineState;

      void startEngine() {
            if(engineState==true) {
                  System.out.println("The engine is already on.");
            }
            else {
                  System.out.println("The engine is now on.");
                  engineState=true;
            }
      }

      void showAtts() {
            System.out.println("This motorcycle is a "+colour+" "+make);
            if(engineState==true) {
                  System.out.println("The engine is on.");
            }
            else {
                  System.out.println("The engine is off.");
            }
      }

}

This compiles ok, but doesn't run in an IE, or java.exe environment. What am I, or the book doing wrong?
Avatar of suprapto45
suprapto45
Flag of Singapore image

Hi,

WHen you run it using java.exe, what does it print?

Regards
Dave
Avatar of Vampireofdarkness

ASKER

Exception in thread "main" java.lang.NoClassDefFoundError: C:\path\to\java\Motorcycle/class
Hi,

It works well on me, what's wrong with you? is there any error in your console?

Regards
Dave
Oh,

That is only the problem of the classpath. Try this, java -classpath . Motorcycle

Regards
Dave
Same thing.. does it matter that the path has spaces even though it is encased in quote?
Okay,

I am just trying to remember what  I did since I do not have any compiler with me now. Sorry ;)

Consider that your Motorcycle.java is on C:\path\to\java\Motorcycle
so

C:\path\to\java\Motorcycle>javac -classpath . Motorcycle.java

C:\path\to\java\Motorcycle>java -classpath . Motorcycle

I hope that worked.

Regards
Dave
Avatar of Harisha M G
Hi Vampireofdarkness,
   
    Do you just have this or some more code in your code ?

    You should import the builtin classes... put these at the beginning...

    import java.io.*;

Bye
---
Harish
Hi Harish,

>>"import java.io.*;"
Why? I do not think that is necessary, isn't it? As far as I can see that it is unnecessary...anyway, please let me know if it is necessary ;)

Regards
Dave
suprapto45,
    That is just a suggestion :)
>>"That is just a suggestion :)"
Okay then ;). Please be with me to help this guy ;)

Regards
Dave
suprapto45 > Same thing as before.
mgh_mgharish > The book only supplied that code segment, so I am to assume that works. If necessary I can scan the page in the book and upload somewhere for reference.
>>"Same thing as before."
Mmmmm....let me take my laptop for a while....10 mins ;)

Regards
Dave
Is it your first program or have you programmed before in Java (using that book) ?
Well, unless you count Hello World! as a program, it's the first one.

The Hello World! worked ok.
So the Hello World worked ok but this one does not work.

And did you use the same way to compile and run it?

Regards
Dave
Okay,

tell us on how do you compile and run it?

Regards
Dave
I have installed JDK + Netbeans.

I made a shortcut to "cmd /k C:\path\to\java\javac.exe" in quick launch. I drag and drop my .java file there. I also made a similar shortcut for java.exe.

I also have a .html which has the applet code in it - returns "not inited" in the status bar and the java.exe returns "Exception in thread "main" java.lang.NoClassDefFoundError: C:\path\to\java\Motorcycle/class"


For both hello world and motorcycle I used the above method.
SOLUTION
Avatar of suprapto45
suprapto45
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I drag and drop the *.java file onto the shortcut for javac.exe which opens (and leaves open (note cmd /k)) the command prompt window for javac.exe with whatever I drag and drop as the path.

This method worked for helloworld, and works, in that it produces a .class file, for motorcycle.
Oh...

I am confused why doesn't it work. But just let you know, there is nothing wrong on your codes. It works, it only the problems on your method to run it.

Regards
Dave
<applet code="Motorcycle.class"></applet> -> index.html in the same folder as Motorcycle.class returns "Applet Motorcycle notinited"

running in java.exe returns
     Exception in thread "main" java.lang.NoClassDefFoundError: C:\path\to\java\Motorcycle/class"

If it is a problem with my method of running said program, what method should I use instead?
I am not sure now. I need to go now...I'll try to help you again in the next few hours time.

Sorry

Regards
Dave
Hmmm.. what you are doing is..

java Motorcycle.java

which is not the way to compile... you should use "javac"
as in

javac Motorcycle.java
Once you compile it using javac, you should use java to run the program in console or appletviewer to run applets.
Please read above..

QUOTE

I drag and drop the *.java file onto the shortcut for javac.exe which opens (and leaves open (note cmd /k)) the command prompt window for javac.exe with whatever I drag and drop as the path.

This method worked for helloworld, and works, in that it produces a .class file, for motorcycle.

UNQUOTE
Okay, it produces a CLASS file; this clearly means that it's been compiled fine (with no problems).

You mentioned that you tried to run it as an Applet: this WON'T work, because you haven't extended the Applet (or JApplet if you're using SWING) class into your application... It will only run as an application from the console..

What I want you to do, is the following:

  Start menu  ->  Run...  ->  "cmd"  ->  ok

This will open the Command Prompt. I now want you to move into the folder containing your CLASS file. This can be done at the Command Line like so:

   CD C:\path\to\java

Now, do the following at the command line:

   java -cp . Motorcycle

If that still doesn't work, then type in the following command:

   set classpath=%classpath%;%cd%

Hit enter, and then type in this command:

   java Motorcycle

And hit enter again...

Let us know what that does..

Ok, so let me just clear something up here.

I HAVE (absolutely MUST) have the class file in the same directory as the java.exe file? It won't work if I don't?

I just tried and it worked.. but it didn't work from the other folder?

I must also C(hange)D(irectory) to the path of the java application  (and now the class file) before attempting to run the application?

This all seems a little silly.

So, everytime I wish to view said application I must (if not already open) run (windows key + r) cmd /k, then cd path/to/java, then java -cp . (classname, no extension)

Eg

windows+r
cmd /k
cd C:\path\to\java
java -cp . Motorcycle

Is there no way in which I can do this through my current shortcut?

You mention the extending applet. Is that a case of simply adding "extends java.applet.Applet" onto the main function?

I'll award the points shortly.. just double checking.
Firstly, the simple one:
> "You mention the extending applet. Is that a case of simply adding "extends java.applet.Applet" onto the main function?"
Not quite... that is how you extend the applet, but you must also override the correct methods ... you should come onto that some more further on in your book...

> "I just tried and it worked.. but it didn't work from the other folder?"
I have never encountered this before... You say that it runs fine if you have the Class file in the same folder as java.exe, and execute it from there; but no where else?!

Can you please run the following command from the Command Line (it doesn't matter what directory you're working in - any will do):

   echo %classpath% - %path% - _%java_home%>_t.txt& notepad _t.txt

That should open notepad, which will have some text in it; please copy and paste the text in that notepad to here...
Oops..

> "Is that a case of simply adding "extends java.applet.Applet" onto the main function?""
No.. You append "extends java.applet.Applet" onto the class declaration:

    class Motorcycle extends java.applet.Applet

But as I've already said; you'd still need to override some methods in order for that to work..
echo %classpath% - %path% - _%java_home%>_t.txt& notepad _t.txt

=

%classpath% - C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\ATI Technologies\ATI Control Panel - _%java_home%
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
So...

My java installation is: C:\j2sdk1.4.2_08(\bin - if necessary)
My java files (applets/programs) are: C:\Documents and Settings\User\Desktop\Java\

I do .;C:\Documents and Settings\User\Desktop\Java\ as my Classpath?

Ok, now when I do cmd /k java Motorcycle it does the correct action. But I still can't drag/drop onto the quick launch icon to do this.

Oh well. If you want to explain, please do so via email : jack.ohara@ntlworld.com

Other than that I believe this case is closed. I'll up points simply because I am relieved.
> "I do .;C:\Documents and Settings\User\Desktop\Java\ as my Classpath?"
Correct.

> "But I still can't drag/drop onto the quick launch icon to do this."
The shortcut method using 'cmd /k java' doesn't work for me either; so it's nothing to get worried about (i.e. it's not a configuration problem on your machine)..

However .. I just created a Batch File for you. Copy and Paste the following code into notepad:


@echo off
title Java Compilation and Execution
if not exist %1 (
   echo Cannot find file %1
   pause>nul
   exit /b
)

cls
echo.

for %%I in (%1) do cd /d "%%~dpI"

for %%I in (%~nx1) do if /i "%%~xI"==".java" javac "%~nx1"
for %%I in (%~nx1) do java %%~nI

echo.
pause>nul


And then save it to wherever you put that "cmd /k java" shortcut (perhaps on the desktop) -- but make sure that you save it with a .BAT extension!

Now, whenever you want to test a program, you can just drag it onto the Batch File shortcut.. *Also*, I've added an extra little feature to it: if you drag a .JAVA source file onto it, it will compile it first, and *then* execute it's CLASS file!! :-)

Good luck with it.
Oh, I've added some extras to that code, just so that you know exactly what's going on when you run it:


@echo off
title Java Compilation and Execution
if not exist %1 (
   echo Cannot find file %1
   pause>nul
   exit /b
)

cls
echo.

for %%I in (%1) do cd /d "%%~dpI"

for %%I in (%~nx1) do if /i "%%~xI"==".java" (
   echo Compiling %~nx1 . . .
   javac "%~nx1"
)

echo Attempting to execute %~n1 . . .
for %%I in (%~nx1) do java %%~nI

echo.
pause>nul