This seems like a simple problem, but somehow I’m having issues with this code. I’m getting back into Java after a few years, and I’m making a 2D game. In it, I have a main driver class called SnakeGame that loads a new instance of the class GameBoard.
SnakeGame.java
package snake2;
import javax.swing.JFrame;
public class SnakeGame extends JFrame {
public SnakeGame() {
add(new GameBoard());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(320, 340);
setLocationRelativeTo(null);
setTitle("Snake Game");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new SnakeGame();
}
}
In the same directory lies GameBoard.java, which has a constructer with no required parameters:
public GameBoard() {
[... more code ...]
}
Edit
Both GameBoard.java and SnakeGame.java have package snake2; at the first line of their files.
However, I keep receiving the following error:
SnakeGame.java:7: cannot find symbol
symbol : class GameBoard
location: class snake2.SnakeGame
add(new GameBoard());
^
1 error
Edit #2
I’ve tried to add it to my class path, using java -cp . GameBoard after javac. Here’s the first line of the terminal’s scary looking and unnecessarily verbose response:
Exception in thread "main" java.lang.NoClassDefFoundError: GameBoard (wrong name: snake2/GameBoard)
This is as if I’ve misspelled the class, or misspelled a file name. Although, to my knowledge, I haven’t done either. Is there some other problem with my code that I haven’t noticed?
Thanks for any help in advance.
Besides being in the same directory, do you have a
packagestatement in GameBoard.java?Edit for running the program —
From @kbolino
You must also invoke java, not just javac, with the correct package and classpath.
Examples that worked for me, after creating SnakeGame and GameBoard stubs:
Current dir is
projectswhich is the parent of thesnake2dir where the files are:java snake2.SnakeGameCurrent dir is
snake2where I was editing the files:java -cp .. snake2.SnakeGameFor case #2 since you’re in the package dir you have to put the parent dir in the classpath.
.
Adding a ridiculous amount of information showing my session with both the
javaccompile command andjavarun. You don’t need-cpfor compiling as suggested by some.Packaging
Package up your application in a
.jarfile along with a Manifest that specifies the main class to run, then you can run your program just usingTo do that, create a file
Manifest.txtin the directory above your package directoryYou can also wrap a script (shell script, batch file, etc.) around that so you just run
myprogramand it runsjava -jar myprogram.jarThis would all be part of your build process.