#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    1
    Rep Power
    0

    GuessGame with three classes


    Hello, I've been struggling with this program that keep running loop forever. It supposed be stop when player get the right guess numbers. I couldn't find what's wrong with my program So, please anyone could help me? It's due this Tuesday, May 7. THANK YOU!!



    package guessgamepackage;

    public class GameLauncher {
    public static void main(String[] args) {
    GuessGame game = new GuessGame();
    game.startGame();
    }
    }





    package guessgamepackage;

    import java.util.*;

    class Player {

    ArrayList playerMemory = new ArrayList();

    public Player() {
    playerMemory.add(-1);
    }
    int number = 0;

    public int guess() {
    number = 50 + (int) (Math.random() * 10);
    while (playerMemory.contains(number)) {
    number = 50 + (int) (Math.random() * 10);
    }
    return number;
    }
    }





    package guessgamepackage;

    public class GuessGame {

    Player p1;
    Player p2;

    public void startGame() {
    p1 = new Player();
    p2 = new Player();

    int guessp1 = 0;
    int guessp2 = 0;

    boolean p1isRight = false;
    boolean p2isRight = false;

    int targetNumber = (int) (Math.random() * 60) + 50;
    System.out.println("I`m thinking of a number between 0 and 9");

    while (true) {
    System.out.println("Number to guess is " + targetNumber);

    p1.guess();
    p2.guess();

    guessp1 = p1.number;
    System.out.println("Player one guessed " + guessp1);

    guessp2 = p2.number;
    System.out.println("Player two guessed " + guessp2);

    if (guessp1 == targetNumber) {
    p1isRight = true;
    }
    if (guessp2 == targetNumber) {
    p2isRight = true;

    if (p1isRight || p2isRight) {
    System.out.println("We have a winner!");
    System.out.println("Player one got it right? " + p1isRight);
    System.out.println("Player two got it right? " + p2isRight);
    System.out.println("Game is over!");
    break;

    } else {
    System.out.println("Players will have to try again.");
    }

    }

    }

    }
    }
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Feb 2004
    Location
    Mobile, Alabama
    Posts
    4,023
    Rep Power
    1285
    Notice in this code

    Code:
    public int guess() {
    number = 50 + (int) (Math.random() * 10);
    while (playerMemory.contains(number)) {
    number = 50 + (int) (Math.random() * 10);
    }
    return number;
    }
    you are forgetting something.

IMN logo majestic logo threadwatch logo seochat tools logo