1

I am a new bee trying my hand at Java.

I am trying to write a small number guessing game where computer picks a number and then 3 players take turns at guessing the number. A number can be guessed only once irrespective of the player who guessed it.

Given below is my complete code. There is some problem in the checkGuess() method (infinite loop) but I can't spot what it is. Can you have a look and see where am I going wrong?

import java.util.ArrayList;

public class game {
private player[] p = new player[3];
private int guess;
private ArrayList<Integer> guesses = new ArrayList<Integer>();

public void start() {
int x=0;
while(x<3) {
    p[x] = new player();
    p[x].setName(x);
    x = x + 1;
}

guess = (int) (Math.random() * 10);
System.out.println("I'm guessing " + guess);

int count = 1;  
while(true) {
    int y = 0;
    boolean b = false;

    while(y<3) {
        boolean searchGuess = true;
        while(searchGuess = true) {
            int temp = p[y].guessNum();
            searchGuess = checkGuess(temp);
            if (searchGuess == false) {
                System.out.println("Player " + (y+1) + " guessed " + p[y].getNum());
            }//end if
        }// end while

        if (searchGuess==false) {
            System.out.println(p[y].getName() + " guessed " + p[y].getNum());
        }//end if

        if (p[y].getNum() == guess) {
            System.out.println("" + p[y].getName() + " guessed correct number in " + count + " guesses. Game over.");
            b = true;
            break;
        }//end if
        y = y + 1;
    }//end loop
    if (b == true) {
        break;
    }        

    count = count + 1;
}//end loop
}//end start

public boolean checkGuess(int tempGuess) {
    boolean found = false;
        if(guesses.contains(tempGuess)) {
            found = true;
        } else {
            guesses.add(tempGuess); 
        }//end if
    return found;
}//end checkGuess
}//end game


public class player {
private int num;
private String name;

public int guessNum() {
    num = (int) (Math.random() * 10);
    System.out.println("in guessnum");
    return num;
}//end guessnum

public void setName(int x) {
    name = "Player " + x;
}//end setName

public int getNum() {
    return num;
}//end getNum

public String getName() {
    return name;
}//end getName
}//end class
Charles
  • 50,943
  • 13
  • 104
  • 142
  • 1
    You don't need to post your entire class. If you think the issue is in the checkGuess method, then only paste that method. – Chris Leyva Dec 25 '13 at 20:29

1 Answers1

5

You're assigning to searchGuess in the condition of the while loop. Instead, use while(searchGuess == true) or simply while(searchGuess).

ales_t
  • 1,967
  • 11
  • 10
  • Remember to accept the answer if you found it helpful. This is generally necessary for the stack idea to work. – 3yakuya Dec 26 '13 at 00:13