I just started working on a Snake game, and I made a Main class, and I made a Display class immediately. I created a package, "Game" for them, but when I compile the Main class, the console says it can't find "Display."
Here is the Main class:
package Game;
public class Main {
public static Display f = new Display();
public static int w = 700;
public static int h = 400;
public static void main( String[] args ) {
f.setTitle(" SNAKE");
f.setSize(w, h);
} // end of method main()
} // end of class Main
Here is the Display class (not completed):
package Game;
import javax.swing.*;
public class Display extends JFrame {
public Display() {
} // end of constructor
} // end of class Display
Consider the directory structure to be :
Project
|
-------------------------
| |
source
| build (this is where compiled stuff will go or resources)
------------
| |
Main.java Display.java
Now from the command prompt, go to Project Directory and write :
javac -d build source\*.java
This will create the package folders inside the build folder automatically (In this case Game Folder will be created automatically containing Display.class and Main.class). Now go into the build folder and run it like this :
java Game.Main
More information regarding the use of javac can be found, by simply typing javac on the terminal. All options with which javac can be used with, will be displayed on the terminal.
Ensure both classes are located in a directory named Game as expected by the compiler.
Side note:
- Follow Java naming conventions for package names and use lowercase letters, e.g. game rather than Game
That package name looks very odd. Try something like com.liamslagle.game instead.
Related
I have two files in the same directory namely Main.java and Functions.java
The content of Main.java is this:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.next();
Functions you = new Functions(s);
System.out.println("Your name is " + you);
}
}
And Functions.java:
public class Functions {
public String name;
public Functions(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
I manually compile and run them on my terminal. So this is what I did:
javac folder1/folder2/*.java
And after
java folder1/folder2/Main.java
But it gives me an error of this:
error: cannot find symbol
Functions you = new Functions(s);
symbol: class Functions
Even though they are on the same directory, it will still give an error.
Edit: I interchanged my code for compiling and running. Sorry for that.
run javac Main.java
run java Main
Note 1: You don't need to explicitly compile the files which are being used in the file you're compiling. If Java compiler sees, that you're using class B in the class A, Java will implicitly compile all the classes (including class B) when compiling the container class (class A, in this case).
Note 2: If you're using JDK >=11, then you can just compile+run the program with one command. JEP 330, Launch Single-File Source-Code Programs, is one of the new features introduced in the JDK 11 release. So, you can just run java ClassName.java.
The issue is classpath.
folder1
| folder2
| | Main.java
| | Functions.java
After you run javac folder1/folder2/*.java you'll have class files.
folder1
| folder2
| | Main.class
| | Main.java
| | Functions.class
| | Functions.java
Since your classes are not in a package then folder2 needs to be on the classpath. To run main.
java -cp folder1/folder2 Main
Notice that I left off the .java on the name of the class.
If you don't want to supply the -cp argument (sets the classpath) you can cd folder1/folder2 then you'll be in the folder with the class files. You can just type.
java Main
I tried this with your java files. When it works you won't see any output until you press enter.
file name first.java
package p1;
public class first
{
int a;
public void display()
{
System.out.println(a);
}
}
second file sec.java
package p2;
import p1.first;
class sec
{
public static void main(String args[])
{
first obj=new first();
obj.display();
}
}
getting this error when i try to run after compilation
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\Users\shaik\Documents\Java> javac -d C:\Users\shaik\Documents\Java first.java
PS C:\Users\shaik\Documents\Java> javac -d C:\Users\shaik\Documents\Java sec.java
PS C:\Users\shaik\Documents\Java> java -classpath C:\Users\shaik\Documents\Java sec
Error: Could not find or load main class sec
file structure must match package structure. You need some directory we'll call 'sourcebase', which contains a dir named p1, and in that dir there needs to be a file named first.java.
Then to run this code after you compiled it, you need a dir we'll call 'classbase', containing a dir named p1, containing a file named first.class. Same goes for your sec class. Once you have all that, you can run:
java -classpath classbase p2.sec
note also that the name of your class is p2.sec. Not sec. No amount of classpath finagling would even make java sec run your app. Within source code, if you're in the same package (so, p2), or you have an import p2.sec; statemente at the top, you get to just type sec to refer to p2.sec but everywhere else, including as argument to the java application, it is called p2.sec.
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
So I've tried to start compiling and running java on sublime, and it works fine if the package is not defined.
this compile and run:
public class Tester
{
public static void main(String[] args)
{
System.out.println("this is a test.");
}
}
But if I add a package:
package test;
public class Tester
{
public static void main(String[] args)
{
System.out.println("this is a test.");
}
}
I got this error
Error: Could not find or load main class Tester
[Finished in 6.8s with exit code 1]
[cmd: ['javac "Tester.java" && java "Tester"']]
[dir: /Users/ph/Documents/JAVA/test]
[path: /usr/bin:/bin:/usr/sbin:/sbin]
Any idea why is this happening or how to fix it?
[cmd: ['javac "Tester.java" && java "Tester"']]
[dir: /Users/ph/Documents/JAVA/test]
Sublime Text is trying to compile your program in a directory called "test" (see #2), which is the package name. It is looking for a file named "Tester.java" within that directory (see #1), but it doesn't exist because "Tester.java" is inside the current directory ("JAVA").
When compiling Java files in packages, the files need to be in a directory structure that reflects the package hierarchy. So you need to move your file to the directory that corresponds to the package it is contained in. For example, class "A" in package example.utils.letters would have to exist at the path ../example/utils/letters/A.java
Create folder "JAVA/test" and move Tester.java into there, then run it.
Ok so I have a file called 'Sandwich.java' at the root folder and a file called 'SandwichType.java' inside of a folder at [root]/MyFrstPkg. For whatever reason it won't compile claiming that Sandwich.java cannot be found. Here is the directory structure:
root --
|
|- Sandwich.java
|
|-MyFirstPkg
|
|-SandwichType.java
Here is Sandwich.java:
//note I also tried adding package MyFrstPkg; in this file as well and removing the leading MyFrstPkg. from the import statement below, still no luck.
import MyFrstPkg.SandwichType; //the text 'MyFrstPkg' part is underlined as an error
class Sandwich{
SandwichType type; //the text 'SandwichType' is underlined as an error
public static void main(String[] args){
Sandwich sndwch1 = new Sandwich();
sndwch1.type = SandwichType.HAM; //the text 'SandwichType' is underlined as an error
System.out.println("A HAM costs $"+sndwch1.type.getCost());
System.out.println("and has "+ sndwch1.type.getSlices()+" slices.");
}
}
and here is SandwichType.java:
package MyFrstPkg;
enum SandwichType{
HAM(0,0f);
SandwichType(int numSlices, float cost){ // constructor - Ryan changed 'numslices' to 'numSlices'
this.numSlices = numSlices;
this.cost = cost;
} //end constructor
private int numSlices; //These are specific to this
private float cost; // enum class...
public int getSlices(){
return numSlices;
}
public float getCost(){
return cost;
}
}//end of SandwichType enum
I browse in CMD to the root location and run 'java Sandwich.java' and all I get is a ClassNotFoundExeption Sandwich.Java, why is it not found? IT IS ITSELF D:
To compile your class, use
javac Sandwich.java
If this gives no error messages, you should be able to call
java Sandwich
to start your program.
If the first works without error, we are one step further. If the second does not work, try this instead:
java -cp . Sandwich
If it works this way, you have set some wrong classpath. Type echo %CLASSPATH% and post the result. (Normally you should not need the CLASSPATH variable at all for simple projects.)
Netbeans is very project-based, so I'd try creating a basic Java Application project and putting them in there.
The name of your project becomes the base package name if you choose "new project" then "java application". You would want to choose "java project with existing sources" if you already have the package/directory structure set up.
If you choose "java application" you can delete the default package name, then right click on the project name, choose "New" Then "Java Package ..." from the list.
EDIT: - Sorry... didn't notice. Your classes aren't public. That's your real problem.
public class Sandwich { ...
public enum SandwichType { ...
As for trying to run java Sandwich.java ... er, you can't. That's source code. It has to be compiled to a class first.