Ray Ban Ray Ban - 7 months ago 11
Java Question

Compare to variable from other class

I tried so hard but I couldn't get this to work. My method "guess" in class "Game" should compare the parameter "someInt" with the variable "x" from the class "Number". I would really appreciate any help, I have to get this done this evening. This is what I got, so far:

public class Number
{
private int x;

/**
* Constructor for class Number.
* This constructor assigns x to a new random
* number between 1 and 100
*/
public Number()
{
// The following lines creates a random number
// between 1 and 100 and assigns it to x
java.util.Random random = new java.util.Random();
x = random.nextInt(100) + 1;
}

public int getNumber(){
return x;
}
}


And my other class:

public class Game
{
private Number number;

/**
* This constructor should initialize the filed number
*/
public Game() {
Number number1 = new Number();
number1.getNumber(x);

}

/**
* This method takes a parameter "someInt" and
* compares it with the value stored in "this.number".
* If "someInt" is less than the value stored in "this.number",
* then the system should print "Your guess is too small" on the screen;
* if "someInt" is larger than that value,
* then the system should print "Your guess is too large" on the screen;
* otherwise it should print "You win!".
*/
public void guess(int someInt) {
if (someInt < x){
System.out.println("Your guess is too small");
}
else if (someInt > x) {
System.out.println("Your guess is too large");
}
else {
System.out.println("You win!");
}
}
}

Answer

Here is a modified version

public class Game
{
private Number number;

/**
 * This constructor should initialize the filled number
 */
public Game() {
   this.number = new Number();

}

/**
 * This method takes a parameter "someInt" and 
 * compares it with the value stored in "this.number".
 * If "someInt" is less than the value stored in "this.number",
 * then the system should print "Your guess is too small" on the screen;
 * if "someInt" is larger than that value,
 * then the system should print "Your guess is too large" on the screen;
 * otherwise it should print "You win!".
 */
public void guess(int someInt) {
    if (someInt < number.getNumber()){
        System.out.println("Your guess is too small");
    }
    else if (someInt > number.getNumber()) {
        System.out.println("Your guess is too large");
    }
    else {
        System.out.println("You win!");
    }    
}
}

On the other hand, you shouldn't use classes with the same names as in java.lang, as Number. It's distracting, making your code hard-readable and bug-genic.

The problems were:

  • Number.getNumber() does not take arguments, you provided one
  • You created a local object number1 while you should be operating on number.
  • In guess(), you used x, instead, Number.getNumber() should be used.

I recommend renaming Number to something not causing name clashes with java.lang.Number.