I have created a simple program to practice polymorphism and inheritance, and it compiles and runs perfectly in a single file. I then split the program into multiple files all in the same package. I was able to compile the files using javac *.java, and it compiled without errors. However when I run the program by typing java zoo_sim i get:
Error: Could not find or load main class zoo_sim Caused by:
java.lang.NoClassDefFoundError: zoo_proj/zoo_sim (wrong name: zoo_sim)
The name of the class containing main is zoo_sim.
The name of the package is zoo_proj.
At the top of each file I have the line:
package zoo_proj;
I am new to java so I'm sorry if I'm missing something stupid here.
Thanks!
Edit: here is my zoo_sim class:
package zoo_proj;
public class zoo_sim {
public static void main(String args[]) {
//create and allocate animal array
Animal animalArray[] = new Animal[3];
//and Leo to animal array
Animal Leo = new Cat("Leo", 4, 13);
animalArray[0] = Leo;
//add Crixus to animal array
Animal Crixus = new Dog("Crixus", 5, 50);
animalArray[1] = Crixus;
//add Peter to animal array
Animal Peter = new Pig("Peter", 3, 100);
animalArray[2] = Peter;
//c style for loop
for(int i = 0; i < animalArray.length; i++) {
System.out.print(animalArray[i].getName() + " is " + animalArray[i].getAge() + " years old and says ");
animalArray[i].makeSound();
}
//print line in between
System.out.println();
//for each style for loop
for(Animal i : animalArray) {
System.out.print(i.getName() + " weighs " + i.getWeight() + " pounds and says ");
i.makeSound();
}
}
}
I'm using linux running in the command line. Here is my output for java -version:
openjdk version "11.0.3" 2019-04-16
OpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu218.04.1)
OpenJDK 64-Bit Server VM (build 11.0.3+7-Ubuntu-1ubuntu218.04.1, mixed mode, sharing)
when I type java zoo_proj.zoo_sim I get:
Error: Could not find or load main class zoo_proj.zoo_sim
Caused by: java.lang.ClassNotFoundException: zoo_proj.zoo_sim
I think your problem is that you're executing java zoo_proj.zoo_sim from within the package directory zoo_proj.
Go one level up and execute java zoo_proj.zoo_sim from the directory one above from zoo_proj.
My steps to reproduce are:
Let my top directory be /zoo.
All files of package zoo_proj are within /zoo/zoo_proj directory,
i.e. the layout is:
/zoo
----/zoo_proj
-------------/Animal.java
-------------/Cat.java
-------------/Dog.java
-------------/Pig.java
-------------/zoo_sim.java
All commands are executed while being in /zoo directory, NOT in zoo/zoo_proj.
To compile java files, execute javac zoo_proj/*.java. On successful execution, zoo_proj should now contain corresponding .class file for each .java file.
Execute java zoo_proj.zoo_sim. Program executes successfully.
If you go to /zoo/zoo_proj and execute java zoo_proj.zoo_sim from here, the output is Error: Could not find or load main class zoo_proj.zoo_sim.
Related
I'm learning Java through the this Princeton course https://algs4.cs.princeton.edu/home/. I've create a simple Java program called Ortho.java using the Java provided by the course (that I installed using this tutorial: https://algs4.cs.princeton.edu/linux/). The program receives two .txt input files, it reads those as a list of strings, and print their first value.
Here's the program:
package edu.princeton.cs.algs4;
import java.util.Arrays;
class Ortho{
public static void main(String args[]){
// Read files from input and print statements
In in = new In(args[0]);
String[] list = in.readAllStrings(); //parse the first text input
while (!StdIn.isEmpty()) {
String key = StdIn.readString();
System.out.print(key);
}
}
}
I run this command on the shell to compile my program, this creates a file called Ortho.class:
javac-algs4 Ortho.java
This is the command I use to run the program:
java-algs4 Ortho.class text_1.txt < text_2.txt
But I always get this error:
Error: Could not find or load main class Ortho.class
Caused by: java.lang.ClassNotFoundException: Ortho.class
What do I need to do to properly compile and run this program with the algs4 Java lib provided by the course?
This is my project structure:
dir/
Ortho.java
Ortho.class
text_1.txt
text_2.txt
Run the program like this :
java algs4.Ortho text_1.txt < text_2.txt
Let me know if this worked for you or no.
When I write a simple parametrised constructor program, it compiles and runs in the command line.
However when it is executed within the Eclipse IDE, I received the following exception:
Exception in thread "main" java.lang.NoSuchMethodError:
a_constructor.Test.(II)V at
a_constructor.ParametrizedConstructor.main(ParametrizedConstructor.java:15).
Code :
//write a java program which listed the concept of parameterized constructor
class Test {
int a,b;
Test (int x, int y) {
a=x;
b=y;
System.out.println("========================");
System.out.println("value of a=" +a);
System.out.println("value of b=" +b);
System.out.println("========================");
}
}
public class ParametrizedConstructor {
public static void main(String[] args) {
Test t1=new Test(10,20);
Test t2=new Test(100,200);
Test t3=new Test(1000,2000);
}
}
The ParametrizedConstructor code is clean and doesn't have any issues.
Try:
Delete the class files which were generated using the command prompt - If you are using the same location through eclipse to compile the same file.
Make sure the Java Compiler and Java Build path was matched with the JDK versions.
Alternate Solutions:
Try placing the code in Eclipse > Java Project > Under default package and run the file.
We need to have the make sure that the compilation unit is matched to the class name ParametrizedConstructor.java (i.e.., public class)
For References - Check also the below links for better understanding:
Possible Causes of 'java.lang.NoSuchMethodError: main Exception in thread "main"'
I can't seem to figure out what is wrong with this code. Eclipse tells me main method isn't declared. and when I run it in java.exe it tells me "could not find or load main class discount.java" I've spent the last half hour looking for a solution but can't seem to figure it out.
import java.util.Scanner;
public class Discount
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int price;
System.out.println("Enter the Price:");
price = scan.nextInt();
System.out.println( price / 4 * 3 );
}
}
The commands I'm using and error I'm getting:
> CD C:\Programing\Misc
> set path=%path%;C:\Program Files\Java\jdk1.8.0\bin
> javac discount.java
> java discount.java
Error: Could not find out or load main class java.discount
Are you using java discount.java? That's likely the issue.
Try these two lines:
javac discount.java
java discount
That should run your main method (assuming that you've correctly named the file discount.java).
--
EDIT: After seeing your comment about changing the class name, you'll want to rename the file to Discount.java. Then run javac Discount.java and java Discount
The filename has to match the classname exactly, so put this in the file Discount.java (discount.java won't work).
Then, from my command-line:
% javac Discount.java
% java Discount
Enter the Price:
^C
Have a look at this file hierarchy and how to compile java on command line
We have a TeamCity (7.0.3) agent running on a 64-bit Windows Server 2008 machine. When we recently upgraded the agent to use Java 7 (1.7.0_10) the builds started failing with the following stacktrace:
Error occurred during initialization of VM
java.lang.ExceptionInInitializerError
at java.lang.Runtime.loadLibrary0(Runtime.java:841)
at java.lang.System.loadLibrary(System.java:1084)
at java.lang.System.initializeSystemClass(System.java:1145)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at java.io.Win32FileSystem.<init>(Win32FileSystem.java:40)
at java.io.WinNTFileSystem.<init>(WinNTFileSystem.java:37)
at java.io.FileSystem.getFileSystem(Native Method)
at java.io.File.<clinit>(File.java:156)
at java.lang.Runtime.loadLibrary0(Runtime.java:841)
at java.lang.System.loadLibrary(System.java:1084)
at java.lang.System.initializeSystemClass(System.java:1145)
The problem seems to be caused by the inclusion of the "-Dfile.separator=\" java option that TeamCity uses in the executable command for the agent. I was able to reproduce the problem by writing a simple "Hello World" class and compiling it on the Windows box and then running the program with the file.separator option (i.e. java -Dfile.separator=\ HelloWorld)
I haven't found any similar bug reports. Has anyone seen anything like this? Has the behaviour of file.separator changed in Java 7?
Furthermore I realise that \ is the default file.separator for Windows anyway so I don't think the agent really needs to use it in the executable command, however I can't see a way in TeamCity to tell the agent not to include it. Is it possible to do this?
Try the JVM command line parameter -Dfile.separator=\/ (i.e., specify both a backward and forward slash).
It looks java.exe now trims trailing \ (back-slash).
I have the following code:
import java.lang.*;
public class test {
public static void main(String[] argz) {
for(String s : argz) {
System.out.println("agg=" + s + "|");
}
System.out.println("prop=" + System.getProperty("prop") + "|");
}
}
I start it with Java 1.7.0_07 and _10:
C:\Java\jdk1.7.0_07\bin\java.exe -cp . -Dprop=z\\ test a\\ b
agg=a\\|
agg=b|
prop=z\\|
and _10
C:\Java\jdk1.7.0_10\bin\java.exe -cp . -Dprop=z\\ test a\\ b
agg=a|
agg=b|
prop=z|
And one more series:
C:\Java\jdk1.7.0_07\bin\java.exe -cp . -Dprop=z\ test a\ b
agg=a\|
agg=b|
prop=z\|
and _10
C:\Java\jdk1.7.0_10\bin\java.exe -cp . -Dprop=z\ test a\ b
agg=a|
agg=b|
prop=z|
I am referring to my previous question but this time I used the java compiler and the compiler compiles the output- it gives a weird output. And this time I used this instead of super.
This is the code of the program.
class Con {
int x = 10;
Con() {
this(2);
System.out.println("x :" + x);
}
Con(int i) {
x = i;
System.out.println("x :" + x);
}
}
class DemoCon {
public static void main(String args[]) {
Con c1 = new Con();
}
}
What do you think is the problem here? Is this a bug in Java?
Java version - 1.6.0 JDK
I used Eclipse to run the program and there is a Class not found exception.
A.java is the file name... We did a minor edit and made a public class called A.java too but the results are same. We further found out that the problem lies in the compiler.
On Windows it seems CON is reserved name and cannot be used for folders/directories or filenames.
The following
print "test" > Con.java
is not working.
Therefor the compiler is unable to create your Con.class and crashes.
From MSDN:
Do not use the following reserved device names for the name of a file:
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names followed immediately by an extension; for example, NUL.txt is not recommended
perhaps the problem exists because CON is a reserved file name (it was on MS-DOS -- see http://support.microsoft.com/kb/31157 http://www.computerhope.com/copyhlp.htm)
How did you compile it? On Win7 32b with Java 1.6 I get:
Type name is not valid. 'Con' is an invalid name on this platform.
Yes it looks like a bug. It compiled very well on my
Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)
environment on Mac OS X.
Maybe we can help further if you tell us whether you are using Sun (Oracle) JDK or OpenJDK?
Problem might be about class name (Con) and file name (A) are different (they should be the same) and you have two classes at the same level in a single file. Anyway, it compiles well on my box.
In java, the class name and file name must be exactly the same. In your case, your class name is Con, therefore, your class file must be Con.java. Since DemoCon is your class with the static void main(String[] args), your java file must be DemoCon.java.
I saved your code as DemoCon.java .
and ran it as
javac DemoCon.java
java DemoCon
o/p was
x :2
x :2