user2337871
user2337871

Reputation: 462

Error when executing java script from CMD

I am working on an online Java Course. We are presently working on building the following instantiation code:

public class NameDriver
{
   public static void main (String[] args)
   {
      //Instantiation
      Name myName = new Name("Scott", "Robert", "Mitchell");
      Name myName1 = new Name("Scott", "Mitchell");
      Name myName2 = new Name("Mitchell");
      Name noName;
      System.out.println("myName: " + myName.toString());
   }
}

For the following the following:

public class Name
{

   private String first;
   private String middle;
   private String last;

   //Constructor Methods
   public Name(String f, String m, String l)
   {
      first = f;
      middle = m;
      last = l;
   }

   public Name(String f, String l)
   {
      first = f;
      middle = "";
      last = l;
   }

   public Name(String l)
   {
      first = "";
      middle = "";
      last = l;
   }

   public Name()
   {
      first = "";
      middle = "";
      last = "";
   }

   public String toString()
   {
      return first + " " + middle + " " + last;
   }
 }

The result when I execute is the error message "Error: Could not find or load main class".

The names of the Java files duplicate the name of the Main Class, so that doesn't seem to be the problem.

I have done a fair bit of research and the recurring theme appears to be that I need to specify a class path using the -cp option. I have attempted this using the complete path name as well as the '.' from the directory in which the codes are located, but to no avail. It is also worth mentioning that the code appears to compile successfully and that the error occurs on execution.

There is a good possibility that I have messed up the code - as I have only just started using Java, I just can't see it, so another set of eyes would be great.

Upvotes: 0

Views: 188

Answers (1)

Ravi Trivedi
Ravi Trivedi

Reputation: 2360

1) Its Java not Javascript

2) You are not compiling and executing it the right way.

ie:

Open command window. Navigate to the folder where your java source files are. And then Run Javac command to compile them.

For ex: Javac *.java

3) Next, to run,

Navigate to the root class folder(where class files are generated). If you are using source dir as root folder for compiled classes then its alright.

Run Java NameDriver to run your program.

Answer Updated:

1) I think you are only compiling main class NameDriver. You need to compile all classes.

For ex: javac *.java. This will compile all classes.

2) You are running it wrong.

You can't mention .java when running a class file. This is wrong >> java -cp . NameDriver.java

This is right >> java NameDriver

Upvotes: 1

Related Questions