i’m studying java(i’m a beginner) in college and we use eclipse. i would like to try other ides but i can’t run code on any other than eclipse.
we do not use a main class, i know that may sound weird, but it works in eclipse (i guess).
we do exercises with arrays matrixes images, colours that kinda stuff. here’s an example:
static boolean[][] chessMatrix(int lines) {
boolean[][] m = new boolean[lines][lines];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m.length; j++) {
if ((i + j) % 2 == 0) {
m[i][j] = true;
} else
m[i][j] = false;
}
}
return m;
}
this code runs perfectly fine on eclipse, we use a debugger made by some college professors
on intelij, for example, it does not even give me the option to run. i have tried importing the src file directly, changed jre/sdk versions and i can’t get it to work. any help is appreciated, thanks!
>Solution :
Method needs to be part of a class, easiest is to create a class with a main method and put your method inside that class.
Example:
public class Main {
public static void main(String[] args) {
chessMatrix(10);
}
static boolean[][] chessMatrix(int lines) {
boolean[][] m = new boolean[lines][lines];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m.length; j++) {
if ((i + j) % 2 == 0) {
m[i][j] = true;
} else
m[i][j] = false;
}
}
return m;
}
}
Given the source above being saved as file "Main.java", you can compile first, then run that using:
javac -d . Main.java
java Main
Never versions of Java (AFAIK 11 and above) can also compile and run source code directly, using
java Main.java
Notes:
- the method above just created and returns a sqare array of boolean, so expect no visible output
- things get complicated when you use multiple source files, packages and external libraries. That’s the time you should consider using build management tools like Apache Maven or Gradle.