samedi 28 février 2015

Calling "guess" variable for two objects in Java



I'm creating a game for homework, and I'm very stuck in the beginning stages. The game takes inputs from two players. The player class controls the guesses by each player. I've been able to correctly set up the player class so that it only accepts the allowed range of inputs.


However, I'm having difficulty calling the guess variable for two player objects. I've tried to determine how to call the value of each guess variable for each object, but it keeps giving me errors. Am I calling the variable correctly? Or is my logic of having two different guesses values for each player object correct? Or is there another way that I need to write the code to have a guess variable for each player?


player class code:



import java.util.Scanner;

public class player {

//handles the input from the player
public player() {

while (true) {

// Prompt the user to guess the number
System.out.println("Enter your guess: ");
Scanner input = new Scanner(System.in);
int guess = input.nextInt();
System.out.println(guess);

if (guess < 0) {
System.out.println("You entered a negative number.
+ "The number you enter must be between 0 and 4. " +
"Please try again. ");
}
else if (guess >= 5){
System.out.println("You entered is greater than 4. "
+ "The number you enter must be between 0 and 4. " +
"Please try again. ");
}
else{
break;
}

} // End of while loop

}//end of player method

}//End of player class


Main code:



public class HW2 {

public static void main(String[] args) {

System.out.println("It's Player A's turn to guess!");
player playerA = new player();
System.out.println(playerA.guess);


System.out.println("It's Player B's turn to guess!");
player playerB = new player();
System.out.println(playerB.guess);

}//end of main


} // end of HW2 class


Thank you in advance for any help!




Aucun commentaire:

Enregistrer un commentaire