Here's my Situation:
I have a folder Structure:
C:\Users\user\Desktop\JavaTraining\Chapter3\examples.
examples is also a folder. Now, I have a file name Calculator.Java in Chapter3 folder with the package statement package Chapter3;. So, from the Command Line I compiled the file from the JavaTraining directory as javac Chapter3\Calculator.java, It compiled and I see a file Calculator.class generated. But when I run the command java Chapter3.Calculator from the JavaTraining Directory. It throwed me an error: Could not find file or load main class Chapter3.Calculator.
Then, I created a sub folder in Chapter3 named examples and copied the Calculator.java into the examples folder and tried compiling and executing the file thinking Chapter3 as the root folder ( executed commands from the Chapter3 directory). No error, the file got executed.
Please can anyone explain me why this happened or what is the reason behind it, I am going mad...
Calculator.java is just a class Calculator with main function trying to find a sum from a printsum function of two variables.
I went through the suggestions provided in http://stackoverflow.com/questions/18093928/what-does-could-not-find-or-load-main-class-mean
According to the above, it was either the syntax mistake ( the way of trying to executing the file) or setting the PATH and CLASSPATH environment variables.
I even tried the echo %CLASSPATH% to see if my CLASSPATH variable is set to current directory. It did show me the . when I executed the echo command from JavaTraining directory.
The file did not execute when I tried Chapter3 folder as root directory, but when I create a subfolder in Chapter3 and made Chapter3 as the root directory, it executed, what might be the reason or what am I doing wrong,
Here is the command line with the output:
C:\Users\vikas\Desktop\JavaTraining>javac Chapter3\Calculator.java
C:\Users\vikas\Desktop\JavaTraining>java Chapter3.Calculator
Error: Could not find or load main class Chapter3.Calculator
C:\Users\vikas\Desktop\JavaTraining>cd Chapter3
C:\Users\vikas\Desktop\JavaTraining\Chapter3>javac examples\Calculator.java
C:\Users\vikas\Desktop\JavaTraining\Chapter3>java examples.Calculator
The sum is 30
C:\Users\vikas\Desktop\JavaTraining\Chapter3>
The Calculator.java file:
// One Package Statement
package chapter3;
// The file in Chapter 3 folder, file in example folder has
//package examples;
// One or more import statements
import java.io.*;
import java.util.*;
// Class Declaration
public class Calculator {
// State. Variables and Constants
int i=10;
long k = 20;
// Behavior, one or more methods
void printSum(){
long sum;
sum = i+ k;
System.out.println("The sum is " + (i+k));
}
public static void main (String[] args) {
Calculator c = new Calculator();
c.printSum();
}
}
When you build a file, it is good to have a build directory, then java will put the class in the correct package layout.
mkdir build
javac -d build path/to/source/Files.java
java -cp build package.name.Files
Related
I'm a relative Java newbie so apologies if the question appears somewhat basic. I've googled high and low for an answer here and I'm not finding anything that's helping.
Problem:
Whilst I'm able to integrate external packages into my Java programs from an IDE environment, I am trying to do run a very basic program from the command line that calls on a separate, basic package file that I have written - and am simply doing all this as I want to have a bottom-up understanding of how package files are related to a main program by Java.
I have a program that sits on my desktop named MyProgram.java:
import org.somepackage;
public class MyProgram {
public static void main(String arguments[]) {
System.out.println("Programme up and running...");
Human myHuman = new Human();
myHuman.scream();
}
Still on the Desktop, I then have another folder which I've named src, inside of which I have created the necessary subfolders corresponding to the package name, i.e. ./src/org/somepackage - and in this location, I have the Human.java file which defines the Human class with the following contents:
package org.somepackage;
public class Human {
public void scream() {
System.out.println("I exist!!");
}
}
I then created a classes folder, again on the Desktop, and ran the following compile command on the command line:
javac -d ./classes/ ./src/org/packagename/Human.java
This ran fine and created - as expected - the Human.class file within the ./classes/org/packagename/ location.
However, where I fall down is when I then try to compile MyProgram.java on the command line, i.e.
javac -cp ".:./classes/" MyProgram.java
As you'll see, my class path contains a reference to the current location (".") for the MyProgram.java file, and it contains a reference to the classes folder ("./classes/") which is the base location for the org.somepackage package inside whose subfolders (./classes/org/somepackage/) on can find the Human.class file.
At this stage, I was simply expecting the java engine to compile MyProgram.java into the program MyProgram.class - but, instead, I get an error:
MyProgram.java:1: error: package org does not exist
I've been following the instructions listed here:
https://www3.ntu.edu.sg/home/ehchua/programming/java/J9c_PackageClasspath.html
and I don't appear to be deviating from the instructions - yet I'm unable to locate an explanation on Stackoverflow or anywhere else as to a possible reason for this compile failure. If anyone has an idea, your help would be very much appreciated.
Thanks,
Your mistake is here
import org.somepackage; <--
public class MyProgram {
public static void main(String arguments[]) {
System.out.println("Programme up and running...");
Human myHuman = new Human();
myHuman.scream();
}
you forgot to import class actually, you need to write this name
import org.somepackage.Human; import all package content import org.somepackage.*; or write full qualified name of class in your code
org.somepackage.Human myHuman = new org.somepackage.Human();
myHuman.scream();
correct mistake:
import org.somepackage.Human;
public class MyProgram {
public static void main(String arguments[]) {
System.out.println("Programme up and running...");
Human myHuman = new Human();
myHuman.scream();
}
after that compile your Human.java by this command:
javac -d classes Human.java
and MyProgram.java
javac -d classes -cp "classes" MyProgram.java
and run MyProgram by
java -cp "classes" MyProgram
I wrote the following piece of code in sublime text on my macbook pro.
I saved the file inside the java folder on my desktop. When I tried to compile the program and tried to execute it, I am getting the fallowing error message " Error: Could not find or load main class Animals ".
Could someone help me in compiling and running this program
package forest;
class Animals{
public static void main(String[] args)
{
Animals s = new Animals();
Sring[] s2 = s.getAllAnimals();
}
public String[] getAllAnimals()
{
String[] s1= {"Lion", "Elephant", "Tiger","Deer","Wolf","Dinosar"};
return s1;
}
}
Make your class Animal as public and rename the file to Animal.java
Your class is in a package called forest so you need to move Animals.java into a directory called forest.
You hava a typo on line 7: Sring[] s2 = should be String[] s2 =.
Compile from the parent directory of forest. Something like this should work
$ javac forest/Animals.java
Run from the parent dir:
$ java forest.Aminals
Your program will have no output when you run it.
Look on your code there is no sring type class in java so change it to String
Sring[] s2 = s.getAllAnimals();
change it to
String[] s2 = s.getAllAnimals();
Everything will be good
try this tutorial Java and the Mac OS X Terminal and Make your class public and also make sure that the file name that contains your source code and the name of your main class is same, your main class is the one that contains main method.
First of all you can name your java file with any name.
Say Sample.java. and let us consider this file is present in D:\work
Go to D:\work folder in cmd prompt.
Keep this in mind :
If you write package forest, then your class has to be public.
So write public class Animals{}
While compiling do this javac -d Sample.java
By doing this the compiler will create the folder "forest" and inside that it will create the Animals.class.
So now in D:\work we have Sample.java file and "forest" folder
Now in your command prompt DO NOT go inside the "forest" folder.
Stay in work folder. D:\work
And Run this command from D:\work java forest.Animals
Explantion::
The name of your class that contains Main method is not Animals. It is forest.Animals This is the fully qualified name of the class. This happened becasue you put a package to it.
So while runnning you must run with fully qualified name
java forest.Animals
The name of your class is not Sample.java. <-- This is just a text file name it anything the complier will not generate a class with name Sample.class because inside this file there is no such class, the class name is Animals. So Animals.class will be generated.
And javac -d Sample.java helps you create the folder structure automatically based on the package.
For example if your class was like this
package com.stackoverflow.samples
public class Animals{
}
And you do java -d Sample.java
The Compiler will create a folder com inside that another folder stackoverflow inside that another folder samples and inside that a file Animals.class
To run this you must run it from outside the the "com" folder with fully qualified name
java com.stackoverflow.samples.Animals
For some reason, I can't run ANY programs that begin with a package declaration.
Let's say I am trying to run a simple program called 'HelloDate.java'.
package Test;
import java.util.*;
public class HelloDate {
public static void main(String [] args) {
System.out.println("Hello, it's: ");
System.out.println(new Date());
}
}
Both HelloDate.java and HelloDate.class are located in the same folder:
/Users/eduarddedu/Desktop/Test
I am trying to run HelloDate from inside the 'Test' folder; 'pwd' returns:
/Users/eduarddedu/Desktop/Test
The CLASSPATH variable is not set to anything: echo $CLASSPATH returns an empty line.
To my mind, I should now be able to run the program with the command:
java HelloDate
But all I get is this: Error: Could not find or load main class HelloDate
I have also tried setting the CLASSPATH to (alternatively) :
/Users/eduarddedu/Desktop
/Users/eduarddedu/Desktop/Test
Still nothing works.
If I delete the package declaration at the begining, I can run the program just fine, from inside the 'Test' folder or from anywhere else, by setting the CLASSPATH variable.
You are running the file from the wrong directory.
Go to /Users/eduarddedu/Desktop and run:
javac Test/HelloDate.java
java Test.HelloDate
You should call java Test.HelloDate from outside the Test folder.
I have created a package:
path : /home/myid/py_ejb
File : XmppMnager.java
package xmpp;
import org.jivesoftware.smack.Chat;
public class XmppManager {
}
Compiled with
javac -d . -classpath .:smack.jar XmppManager.java
File: XmppTest.java
import xmpp.*;
public class XmppTest {
public static void main(String[] args) throws Exception {
String username = "testuser1";
String password = "testuser1pass";
XmppManager xmppManager = new XmppManager("myserver", 5222);
..}
Compiled with
$ javac -classpath .:smack.jar:./xmpp XmppTest.java
XmppTest.java:10: cannot access XmppManager
bad class file: RegularFileObject[./xmpp/XmppManager.class]
class file contains wrong class: xmpp.XmppManager
Please remove or make sure it appears in the correct subdirectory of the classpath.
XmppManager xmppManager = new XmppManager("myserver", 5222);
^
1 error
I tried a lot of way to fix this compilation issue but it just does not go away
Move the source files into a folder named xmpp so that the package names match that of the folder
Package names are directly related to the classpath directory structure. All the classes in the xmpp package need to be in a folder named xmpp, and this folder must be on the classpath. Similarly, if you had a package called xmpp.util.io you would have to put the files in xmpp/util/io/.
The usual convention is to make a src directory to hold all your source files, and then that can be filled with a directory structure that exactly matches your package structure. A pretty decent tutorial on packages can be found here.
Also, it looks like this is probably just a typo in the question, but if your file is actually named XmppMnager.java rather than XmppManager.java, that won't compile either.
I created the project in NetBeans (according to the book P. Noutona, G. Shildta "Java2. The fullest management"), having specified as an Example2 project name.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package example2;
/**
*
* #author Asus
*/
/*
* Другой короткий пример.
* Файл "Example2.java"
*/
public class Example2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int num; //объявляет переменную с именем num
num=100; //присваивает num значение 100
System.out.println("Значение num: "+num);
num*=2;
System.out.print("Удвоенное значение num: ");
System.out.println(num);
}
}
In case of creation of the project the class example2.Example2 with the D:\ExamplesFromBook\Example2\Example2 project folder (and project layout according to D:\ExamplesFromBook\Example2) was created. I created byte code by means of a command in command line
D:\ExamplesFromBook\Example2\Example2\src\example2>javac Example2.java
therefore the Example2.class file was created. Further I tried to launch various methods.class the file from command line among which, for example, I was such:
D:\ExamplesFromBook\Example2\Example2>java example2.Example2
therefore received an error
Error: Could not find or load main class example2.Example2
What command needs to be used and from what folder to launch?
Your problem lies within the package names. The class you are compiling is inside the package example2 and is called Example2, therefor it's full path is example2.Example2. So far so good. The problem is how java will find the class. Java will transform the package declaration in the command into a file path, in this case example2/Example2.class. Since your class is placed at Example2.class and not at example2/Example2.class, it will not be found and cause an error.
To fix this, create a subdirectory called example2 and place the class file in there.
go to directory D:\ExamplesFromBook\Example2\Example2\src\
then type java -cp D:\ExamplesFromBook\Example2\Example2\src example2.Example2
The main directory where all your class files will lie should be in classpath ( which is D:\ExamplesFromBook\Example2\Example2\src in your case ). Alternatively you can set classpath using your windows Environment variables also. Once that is done; you can run any of your class file using
java <full qualified class name>
for example
java example2.Example2
You are here
D:\ExamplesFromBook\Example2\Example2\src\example2
When you compile
javac Example2.java
the classes will appear in
D:\ExamplesFromBook\Example2\Example2\src\example2
Try dir and list them
Dir D:\ExamplesFromBook\Example2\Example2\src\example2
Now to run a class, it must be in the class path. The lookup will add fully qualified name of class (with dot replaced with / ) and search in every path. In your case
java -cp D:\ExamplesFromBook\Example2\Example2\src example2.Example
should work.
The java program will look for example2/Example2.class under all classpaths you give. See more details at wiki
Change your java compile command
To compile use
javac -d . ClassName.java
to run java class file with package name use
java packageName/className
OR
java packageName.className
Have you tried to compile your .java file to another folder, for xample to "build" as it is done usually?
When Netbeans compiles files automatically it creates the following structure:
"proj_dir"/src/"package"/"code".java
"proj_dir"/build/classes/"package"/"code".class
Try doing it like this, but manually. Then go to "build/classes" dir from command line and type:
java "package"."code"
This is general way to run compiled java-code.
In your case it has to look like:
D:\ExamplesFromBook\Example2\Example2\src\example2\Example2.java
D:\ExamplesFromBook\Example2\Example2\build\classes\example2>Example2.class
CMD commands to do it:
cd D:\ExamplesFromBook\Example2\Example2\src\example2
javac -d ..\..\build\classes Example2.java
cd D:\ExamplesFromBook\Example2\Example2\build\classes
java example2.Example2
It works with simple programs.