2

I'm just beginning to learn java, I created an object counter:

public class Counter 
{
    private int value;
    public void setCounter(int count)
    {
        value = count;
    }
    public void click()
    {
        value = value + 1;
    }
    public int getValue()
    {
        return value;
    }
    public void reset()
    {
        value = 0;
    }
}

When I tried to creat an object of Counter into my Driver class it gave me the error: Exception in thread "main" java.lang.Error: Unresolved compilation problems: Counter cannot be resolved to a type Counter cannot be resolved to a type at Driver.main(Driver.java:4)

public class Driver {
    public static void main(String[] args) {
        Counter count = new Counter();
        count.setCounter(0);
    }
}

I'm not sure if this is necessary but I use eclipse.

Edit: I copied and pasted both of the classes into new classes in a different project and it worked so I think it might have something to do with eclipse rather that my code.

  • 1
    well you are not really importing Counter class at all. Need more information about package structure. import ....Counter; seems to be missing – Bela Vizer Sep 25 '16 at 17:55
  • I guess it is related to the internal Eclipse compiler as suggested here: http://stackoverflow.com/questions/1124788/java-unresolved-compilation-problem – Gil Vegliach Sep 25 '16 at 17:56
  • @MichaelPickett: Java generates no-arg constructor if there are no constructors declared in code. – Gil Vegliach Sep 25 '16 at 17:56
  • If the classes `Counter` and `Driver` are in the same package then you do not need to import class `Counter` at all - classes in the same package automatically can see each other. – Jesper Sep 25 '16 at 18:01
  • @BelaVizer: true, but even with a missing import the compiler would give an error. This problem looks like a runtime-error instead. Btw the classes could also be both in the default package. My bet is on the Eclipse compiler. Clean build to solve. – Gil Vegliach Sep 25 '16 at 18:01

2 Answers2

2

Check if you have imported your Counter class - not the one from built-in libraries (org.w3c.dom.css.Counter).

Wojtek
  • 1,288
  • 11
  • 16
0
  1. I think both the counter and driver are in different packages.
  2. If both the classes are in same package and the counter class may not have been saved and so .class is not generated(In eclipse when you save any class then it will generate .class by default)
  3. if both the classes in different package then you need to import counter class
SpringLearner
  • 13,738
  • 20
  • 78
  • 116