Package missing in basic package structure in Java - java

I have a basic package structure. I have Main class and Player class in first package 'pack1' and then in subdirectory 'pack2' I have a Monster class. I need to use javac and java commands when running this program because it's my homework, but it just tells me that package pack1.pack2 does not exist. I am trying to run it by using command 'javac Main.java'. If I remove packages and place them in the same folder, then the command 'javac Main.java' works fine. When I run this program by using Visual Studio Code "Run" command it runs fine.
My file structure looks like this:
pack1
|_ Main.java
|_ Player.java
|_ pack2
|_ Monster.java
I have been fighting with this for the past 2 hours now, trying to google different solutions but with no luck. I am probably using the javac command in a wrong way. I have tried using -d argument and some path arguments, but since I don't understand them clearly it probably was not the correct way of using them.
package pack1;
import pack1.pack2.Monster;
public class Main extends Monster {
public static void main(String[] args) {
killPlayer();
}
}
package pack1;
public class Player {
public void shout() {
System.out.println("Shout");
}
}
package pack1.pack2;
import pack1.Player;
public abstract class Monster {
public static void killPlayer() {
Player p = new Player();
p.shout();
}
}

on pack1 parent folder:
Compile all your java files.
javac $(find . -name "*.java")
And then,
java pack1.Main

Related

Java | Custom Created Package Does not Exist

Purpose
I want to be able to create a package and call it.
Alternatively, I would like to create separate files for my method (to avoid having x classes in one file).
Setup
Here is my LetterGrader.java file:
package grade.util;
import java.util.*;
import java.io.*;
public class LetterGrader {
private void readArgs() {
System.out.println("Hello, read CLA!");
}
}
Here is my TestLetterGrader.java file:
import java.util.*;
import java.io.*;
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Steps Taken
First, I compile LetterGrader:
This auto creates the bin/grade/util/LetterGrader.class file
javac -d bin -sourcepath src src/grade/util/LetterGrader.java
Here is my working directory at this point
Second, I compile TestLetterGrader:
This fails
javac -d bin -sourcepath src src/grade/util/TestLetterGrader.java
The error message:
src/grade/util/TestLetterGrader.java:6: error: cannot find symbol
LetterGrader letterGrader = new LetterGrader(); // instantiate
^
symbol: class LetterGrader
location: class TestLetterGrader
Question
I believe I am misunderstanding how to call a classes from separate files (in the same location). How can I accomplish this?
You are importing class that is in bin folder. Don’t do that it would not work. You don’t need any import, because the classes are in the same place. Make package under src folder and place the classes there. Remove package grade.util and rename it to the package where you place the classes.
File structure:
src
\
\
yourpackage
\
\
LetterGrader.java TestLetterGrader.java
Then delete everything in your build folder and compile the classes. Java will make it’s magic. You do need to worry about bin folder, it is only for storing compiled classes.
Classes will look like this:
//package name that you created
package yourpackage;
public class LetterGrader {
//need to be public when calling from another class
public void readArgs() {
System.out.println("Hello, read CLA!");
}
}
And
//folder that you placed the .java files
package yourpackage;
//without any import
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Your second question:
You can use classes from other folders, but you you have to import them and they have to be under src folder.
Tell you have class A.java in folder Second and class B.java in folder Main. You will import the the folder in this case import Second.A;
And then call the class A a = new A();
When you have method in a that you want to call simply do:
a.yourmethod();
You have to change private void ... to public void... because you cannot call private outside of the class.
When you are running compiled classes they have to be in the same folder.
Thanks #maratonec for the guidance.
My initial mistake was that I was misunderstanding/misassigning the classpath assignment variable when running a program via terminal. The below helped me.
Compiling and Running a Java Program (on a PC)
• Set the working directory (say, JavaBook)
C:\> cd JavaBook
• Compile HelloWorld.java
C:\JavaBook> javac -d bin src\HelloWorld.java
•Run the program
C:\JavaBook> java -classpath bin HelloWorld
Also, the approach of having all my class files in the same location simplified things. I didn't have to worry about classpath. But not ideal as I have many files to work with.
As for the package creation, I am going to play around with java a bit more before using it. I think I need to solidify my understanding.
Thanks for helping me!

Trouble running java app from cmd

I have two files, app.java and test.java
They both reside in the same package, and they compile just fine with "javac app.java test.java"
Two class files are then created.
However, when I go to run them with the command "java app" because app has the main method, I get "Error: Could not find or load main class app"
app.java:
package working_directory;
public class app {
public app() {
}
public static void main(String [] args) {
test testing = new test();
System.out.println(testing.calculate(60));
}
}
This Is the test.java
package working_directory;
public class test {
public test() {
}
public int calculate(int x) {
return (int) x * x * x;
}
}
Make sure to choose the right path for compilation and running code:
D:\
+--Folder(start cmd here)
+---working_directory
+----app.java
+----test.java
How to compile
D:\Folder\>javac working_directory\*.java
How to run
D:\Folder\>java working_directory.app
To use the java command, you must specify the fully qualified name of the class you want run. This means that you need to specify the package name as well.
You should run this:
java working_directory.app
Since working_directory is the package name.
You must provide a classpath, when running it from command line:
(for windows)
java -classpath . app
You have a package name declared in other words that's a folder. Your project should look like this then
C:\YourProject
C:\YourProject\working_directory
C:\YourProject\working_directory\app.java
Your Project starts at root level so it's C:\YourProject there you have to use the command line and type java working_directory.app

can someone help me to know jdk version compatibility on org.reflections.Reflections jar

I m using Reflections.jar for the first time, so i like to know the following
Is there any version compatibility for this jar(like above jdk6 (or) upto jdk8)
While loading classes is there any order of loading(like alphabetical order (or) order of jar placed in classpath)
If you are talking about this https://github.com/ronmamo/reflections project then it find the classes in the order they appear in your classpath like the Java launcher would do. The way how classes are found and loaded is described here https://docs.oracle.com/javase/8/docs/technotes/tools/findingclasses.html.
The first class file in the classpath order which matches the full class name is loaded. Find a small snippet below for demonstration.
assume following directories and files
lib/annotations-2.0.1.jar
lib/guava-15.0.jar
lib/javassist-3.18.2-GA.jar
lib/reflections-0.9.9.jar
src/DummyInterface.java
src/Main.java
src1/DummyClass1.java
src2/DummyClass1.java
src/DummyInterface.java
package sub.optimal;
public interface DummyInterface {}
src/Main.java
import org.reflections.Reflections;
import sub.optimal.DummyInterface;
public class Main {
public static void main(String[] args) throws Exception {
Reflections reflections = new Reflections("sub.optimal");
for (Class c : reflections.getSubTypesOf(DummyInterface.class)) {
System.out.println("class: " + c.getCanonicalName());
c.newInstance();
}
}
}
src1/DummyClass1.java
package sub.optimal;
public class DummyClass1 implements DummyInterface {
static {
System.out.println("touched DummyClass 1");
}
}
src2/DummyClass1.java
package sub.optimal;
public class DummyClass1 implements DummyInterface {
static {
System.out.println("touched DummyClass 2");
}
}
first compile the classes, for the demonstration we create the class files in different locations
javac -cp lib/* -d bin/ src/DummyInterface.java src/Main.java
javac -cp bin/:lib/* -d bin1/ src1/DummyClass1.java
javac -cp bin/:lib/* -d bin2/ src2/DummyClass1.java
executing Main with bin1/ before bin2/ in the class path will find and load the DummyClass1 in bin1/
java -cp bin/:bin1/:bin2/:lib/* Main
output
class: sub.optimal.DummyClass1
touched DummyClass 1
executing Main with bin2/ before bin1/ in the class path will find and load the DummyClass1 in bin2/
java -cp bin/:bin2/:bin1/:lib/* Main
output
class: sub.optimal.DummyClass1
touched DummyClass 2
1) According to https://github.com/ronmamo/reflections/blob/master/pom.xml, it is compiled with java 1.7, so it is compatible with java version >=1.7
2) http://javarevisited.blogspot.ru/2012/07/when-class-loading-initialization-java-example.html

command line error when trying to use java package

I'm learning java packages in school and I'm able to create and use my package on netbeans perfectly but cannot do it from the lubuntu command line. I get an error: could not find or load main class. Here is the code but I know this is not the problem since it works perfectly in netbeans
package animals;
public class MammalInt implements Animal
{
public void eat()
{
System.out.println("Mammal eats");
}
public void travel()
{
System.out.println("Mammal travels");
}
public static void main(String args[])
{
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
package animals;
interface Animal
{
public void eat();
public void travel();
}
I first compile Animal.java and put the Animal.class file into a directory
animals. I then compile MammalInt.java. If I do not put the Animal.class file in a animals directory it will not compile MammalInt.java . After I have both class files into the animals directory I do java animals/MammalInt and get the error: cannot find or load main class. I also have doe java MammalInt and get the same error. This is really frustrating. Please help.
When compiling (a set of files) you need to use the path.So use /
javac animals/*.java
When running the Java class, you need to specify the Java name of the class.
In your case this is done as follows:
java animals.MammalInt
This says you want the class MammalInt in the package animal. Depending on your installation you also need to add your current directory to your classpath (this is where java looks for .class files), resulting in:
java -cp . animals.MammalInt
Note that you run all commands from the root of your source code tree. This means the directory that contains the directories for your packages. So if you have the following direcotries:
project/
project/animals/
project/animals/Animal.java
Then run the commands from the project/ directories.

How to create a package directory in Java

I am extremely new in Java and I couldn't get one thing straight. I have E:\Java\ACP\Cricket\ directory where I have a Main.java, Player.java and CricPlayer.java. Now I am inheriting Player class into CricPlayer.
I have Main.Java as
import Java.ACP.Cricket.*;
public class Main
{
public static void main(String[] args)
{
System.out.println("Hello.");
}
}
CricPlayer.java As...
import Java.ACP.Cricket
public class CricPlayer extends Player
{
}
I need to use objects of CricPlayer in Main.java. As I mentioned earlier I am real new to Java so there might be some really obvious mistakes that I don't know about. But the question is how can I create a package for use in CricPlayer.java and Main.java? Because each time I compile the code using CMD it says "CricPlayer.java:6: error';' expected import java.ACP.Cricket.*" and points ^ to *. I don't know if I haven't created the Package properly or if it's some syntactical issue.
you need to add package declaration in the beginning of your code files. And you don't need imports if all the classes reside in the same package. BTW, good coding convention in java recommends that all letters in package name are lowercase :)
package Java.ACP.Cricket;
public class Main
{
// Your class contents
}
in the class below you shourd write a package (folder in project where file is situated)
for example
package ACP.Cricket;
You forgot the ; at your import in CricPlayer class:
import Java.ACP.Cricket.*;
Now you should be able to create CricPlayer Objects in your Main Class.
Also I don't know if "Java" in your package name is supposed to be capitalized or not. Seems like the compiler is expecting a lower case 'J' from your naming convention
Here's an alternative to your Programs.I've verified this myself, so you can be assured that it will work.
Important thing you need to know, is that any file can be compiled only if you have a main method for that file(ie in that class). so here's a detailed 'How to do it':
PlayerDemo.java:
package Java.ACP.Cricket;
class Player{
//class members & methods
}
class PlayerDemo{
public static void main(String[] args){
System.out.println("Player Class");
}
}
CricPlayerDemo.java:
package Java.ACP.Cricket;
class CricPlayer extends Player{
// class members & methods
}
class CricPlayerDemo{
public static void main(String[] args){
System.out.println("CricPlayer Class");
}
}
Main.java:
package Java.ACP.Cricket;
class Main{
public static void main(String[] args){
System.out.println("Main Class");
//use other class objects here directly.
}
}
In E: , do following stepwise:
1> javac PlayerDemo.java (this creates Player.class & PlayerDemo.class)
2> copy Player.class to Cricket folder.
3> javac CricPlayerDemo.java (this creates CricPlayer.class & CricPlayerDemo.class)
4> copy CricPlayer.class to Cricket folder.
5> javac Main.java
6> copy Main.class to Cricket folder.
7> now,also in E:, java Java/ACP/Cricket/Main
Instead of compiling from E:, you can also compile from Cricket,to avoid copying class files,but it wont work for CricPlayerDemo.java, as CricPlayer extends Player(whose location is acc to package) so you'll have to compile CricPlayerDemo from E:
Vincenzzochi is right, packages are lower case (but it should not break compilation).
And you need to declare the package at the begining of all your classes :
package java.acp.cricket;
And while all your source files are in the same package, you don't have to import anything!

Categories

Resources