Nuke
Nuke

Reputation: 83

Cannot reference class in Java Code

I have a problem compiling a code for an university lecture.

There is the file Test. java given and may not be changed:

package sorting;
import java.util.*;

class Test {

static final int BOUND_RANDOM = 99;

public static void main(String[] args) {
    System.out.print("n = ");
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    Random random = new Random(123);
    Rectangle[] rectangles = new Rectangle[n];
    for (int i = 0; i < rectangles.length; ++i) {
        // 1. Parameter = x-Koordinate linke untere Ecke
        // 2. Parameter = y-Koordinate linke untere Ecke
        // 3. Parameter = Breite
        // 4. Parameter = Hoehe
        rectangles[i] = new Rectangle(random.nextInt( BOUND_RANDOM),
                                      random.nextInt( BOUND_RANDOM),
                                      random.nextInt( BOUND_RANDOM) + 1,
                                      random.nextInt( BOUND_RANDOM) + 1);
    }
    System.out.print("Vor Sortieren:");
    System.out.println(Arrays.toString(rectangles));
    // long start = System.currentTimeMillis();

    SortingAlgos.selectionSort(rectangles);
    // SortingAlgos.insertionSort(rectangles);
    // Arrays.sort(rectangles);

    // long end = System.currentTimeMillis();
    //System.out.println("Benoetigte Zeit: " + (end - start) + " Millisekunden");
    System.out.println("Nach Sortieren:");
    System.out.println(Arrays.toString(rectangles));
}

}

Next I wrote a file in which I define the class Rectangle, saved in the same folder. I create a Constructor, based on the call in Test.java and I save and compile the file in the same folder as Test.java:

package sorting;
public class Rectangle{

int x,y,width, height;


public Rectangle(int x, int y, int width, int height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
}


public String toString(){
return "x="+this.x;
}


}

Can anyone give me a quick shot, of where am I going wrong?

PS: The problem is I get an error while compiling Test.java where class Rectangle is a not found symbol. I also got this error in Linux and Win 10.

Upvotes: 0

Views: 798

Answers (2)

xtratic
xtratic

Reputation: 4699

From the directory with your sources:

run javac Test.java Rectangle.java or just javac *.java

Your classes need to know about each other. Rectangle has no dependencies on outside classes, so it compiles fine on its own. But Test depends on Rectangle but doesn't know about the class, so compiling them together will fix this.

Upvotes: 1

Varun Naik
Varun Naik

Reputation: 160

The Test class in under package 'sorting'. Your class Rectangle also should be under package 'sorting'

You need to put the classes in folder called as sorting. Then go a one level up and then compile your classes from there.

javac sorting/Rectangle.java
javac sorting/Test.java

Upvotes: 2

Related Questions