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?
LVL 9
VampireofdarknessAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

suprapto45Commented:
Hi,

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

Regards
Dave
VampireofdarknessAuthor Commented:
Exception in thread "main" java.lang.NoClassDefFoundError: C:\path\to\java\Motorcycle/class
suprapto45Commented:
Hi,

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

Regards
Dave
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

suprapto45Commented:
Oh,

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

Regards
Dave
VampireofdarknessAuthor Commented:
Same thing.. does it matter that the path has spaces even though it is encased in quote?
suprapto45Commented:
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
Harisha M GEngineerCommented:
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
suprapto45Commented:
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
Harisha M GEngineerCommented:
suprapto45,
    That is just a suggestion :)
suprapto45Commented:
>>"That is just a suggestion :)"
Okay then ;). Please be with me to help this guy ;)

Regards
Dave
VampireofdarknessAuthor Commented:
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.
suprapto45Commented:
>>"Same thing as before."
Mmmmm....let me take my laptop for a while....10 mins ;)

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

The Hello World! worked ok.
suprapto45Commented:
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
suprapto45Commented:
Okay,

tell us on how do you compile and run it?

Regards
Dave
VampireofdarknessAuthor Commented:
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.
suprapto45Commented:
And how do you compile your Motorcycle.java? Is Motorcycle.class is in C:\path\to\java?

Regards
Dave
VampireofdarknessAuthor Commented:
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.
suprapto45Commented:
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
VampireofdarknessAuthor Commented:
<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?
suprapto45Commented:
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
Harisha M GEngineerCommented:
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
Harisha M GEngineerCommented:
Once you compile it using javac, you should use java to run the program in console or appletviewer to run applets.
VampireofdarknessAuthor Commented:
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
InteractiveMindCommented:
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..

VampireofdarknessAuthor Commented:
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.
InteractiveMindCommented:
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...
InteractiveMindCommented:
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..
VampireofdarknessAuthor Commented:
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%
InteractiveMindCommented:
Ah .. I think I've figured it!

You haven't setup your CLASSPATH variable on your System...

Right-Click "My Computer"  ->  Select "Properties"  ->  click on the "Advanced" tab  ->  click on the "Environment Variables" button  ->  add a "New" variable, called "Classpath", with the following value:

   .;c:\where\my\class\file\is

Save that.. and then exit all open "Command Prompt" instances, and java programs.. and then try again..

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
VampireofdarknessAuthor Commented:
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.
InteractiveMindCommented:
> "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.
InteractiveMindCommented:
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

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.