Random generator always amounting to 0 (Java) - java

I am working through Head First Java, and my Random generator is amounting to 0. Here are my classes:
This is my class with the main method.
public class GameLauncher {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
This is my player object class:
import java.util.Random;
public class Player {
int number = 0; //Where the guess goes
public void guess() {
//random1 is in GuessGame
Random random2 = new Random();
int number = random2.nextInt(10);
System.out.println("I'm guessing " + number);
}
}
Finally, this is the class where most of the code is happening.
import java.util.Random;
public class GuessGame {
//Guessgame has three instance variables for the three Player objects
Player p1;
Player p2;
Player p3;
public void startGame() {
//Create three Player objects and assign them to the three Player instance variables
p1 = new Player();
p2 = new Player();
p3 = new Player();
//Declare three variables to hold the three guesses the players make
int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
//Declare three variables to hold a true or false based on the player's answer
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
//Make a "target" number that the players have to guess
Random random = new Random();
//Generate a number between 0 and 9
int targetNumber = random.nextInt(10);
System.out.println("I'm thinking of a number between 0 and 9...");
while (true) {
System.out.println("Number to guess is " + targetNumber);
//Call each player's guess() method
p1.guess();
p2.guess();
p3.guess();
/*
Get each player's guess (the result of their guess() method
running) by accessing the number variable of each player
*/
guessp1 = p1.number;
guessp2 = p2.number;
guessp3 = p3.number;
System.out.println("Player one guessed " + guessp1);
System.out.println("Player two guessed " + guessp2);
System.out.println("Player three guessed " + guessp3);
/*
Check each player's guess to see if it matches the target number. If a player is right, then set that player's variable to be true (remember, we set it false by default)
*/
if (guessp1 == targetNumber) {
p1isRight = true;
}
if (guessp2 == targetNumber) {
p2isRight = true;
}
if (guessp3 == targetNumber) {
p3isRight = true;
}
//If player one OR player two OR player three is right... (the || operator means OR)
if (p1isRight || p2isRight || p3isRight) {
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("Player three got it right? " + p3isRight);
System.out.println("Game is over.");
break; //Game over, so break out of the loop
}
else {
//We must keep going because nobody got it right!
System.out.println("Players will have to try again.");
} //end if/else
} //end loop
} //end method
} //end class
I am new to these forums, so if I did something wrong please let me know :)
Does anyone know why this isn't working?
Thanks,
Lyfe

You are storing random number in local variable and you think you set it in instance variable
at line
int number = random2.nextInt(10);
change it to
this.number = random2.nextInt(10);
that atleast solves stated problem.
Also See
Java Variables

Related

Starting out with OOP -Dice game question

Hi I am trying to grasp object oriented programming (OOP).
I am making a die game, but I am a little stuck -
package ch6CLASSES;
import java.util.Scanner;
public class getDie {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("A simple dice game.");
int COUNT =10;
for (int i=0;i<COUNT;i++) {
Die userDie = new Die();
System.out.println("user: "+userDie.getValue());
Die computerDie = new Die();
System.out.println("computer: "+computerDie.getValue());
System.out.println();
}
}
}
So I have another class where I calculated everything - but now my question is... within the for loop I had I would like to make a running count of how many times the computer or user wins after each round, any help?
First off you need to have some way to determine whether the computer or user wins. (Since you are practicing OOP a method would probably be most appropriate) Looking at your code it looks like each Die will only have one value, so you have to keep recreating objects. I would recommend having a roll() method that would return a random number between 1 and 6. That way you wouldn't have to create new objects on each iteration of the loop.
Second you'll need a method to determine is the user won. One easy way to do this would be to have the method accept an int parameter and then compare it to the value of the current Die object. Here are some code to get you started in the right direction:
public int roll() {
//generate random number
}
public boolean wonRoll(int value) {
if(this.getValue() > value) {
return true;
} else {
return false;
}
}
And then in your loop:
int computerWins = 0;
int userWins = 0;
Die userDie = new Die();
Die computerDie = new Die();
for (int i=0;i<COUNT;i++) {
System.out.println("user: "+userDie.getValue());
System.out.println("computer: "+computerDie.getValue());
if(userDie.wonRoll(computerDie.getValue()) {
userWins++;
} else {
computerWins++;
}
}
System.out.println("Computer won " + computerWins + " many times");
System.out.println("User won " + userWins + " many times");

Object Oriented Approach for a simple game

I am working on building a simplified version of this game. The problem states that you can have a computer that is smart or stupid but i have decided that to exclude that feature for now and decided to only go with a computer that picks a random amount of objects. I posted a question earlier and worked on it. (https://softwareengineering.stackexchange.com/questions/244680/object-oriented-design-of-a-small-java-game/244683#244683)
So initially i only had designed one class. But now i have designed 3 classes as stated by the problem. I have a pile class , a player class and a game class (also my main class).
I have so far coded the Pile and Player class. I started coding the Game class aswell however i am stuck now as i dont know how to make the game class interact with the Player and Pile class. I basically determine who's turn it is first and then rotate turns till the pile of objects is complete and declare a winner...I don't know how to make the different classes interact with each other . SO i would highly appreciate if someone can guide me further and help me finish this simple game.
I sincerely apologize if i have asked a bad question. This is my first such program i am doing in java dealing with multiple classes so it is a little confusing. I do not want anyone write code but even mentioning or telling me i should make so and so methods etc will be great !
HERE IS THE CODE I HAVE SO FAR.
PILE CLASS
package Nim;
import java.util.Random;
public class Pile {
private int initialSize;
public Pile() {
}
Random rand = new Random();
public void setPile() {
initialSize = (rand.nextInt(100 - 10) + 10);
}
public void reducePile(int x) {
initialSize = initialSize - x;
}
public int getPile() {
return initialSize;
}
public boolean hasStick() {
if (initialSize > 0) {
return true;
}
else {
return false;
}
}
}
PLAYER CLASS
package Nim;
import java.util.Scanner;
import java.util.Random;
public class Player {
public static final int HUMAN = 0;
public static final int COMPUTER = 1;
private int type;
public Player(int theType) {
type = theType;
}
Scanner in = new Scanner(System.in);
// n is number of marbles left in the pile
public int makeMove(int n) {
int max = n / 2;
int grab;
if (type == HUMAN) {
System.out.println("There are " + n
+ " marbles in total. However you can only"
+ "grab no more than " + max + " marbles");
System.out.println("Please Enter the number of marbles to grab: ");
grab = in.nextInt();
while (grab > max || grab < 0) {
System.out.println("You have entered a illelgal value. Please enter a legal value: ");
grab = in.nextInt();
}
return grab;
}
else {
Random rand = new Random();
grab = (rand.nextInt(n / 2 - 1) + 1);
System.out.println("Computer has grabbed: " + grab + " marbles");
return grab;
}
}
public void updateTurn(int n) {
type = n;
}
}
GAME CLASS (in progress)
package Nim;
import java.util.Scanner;
import java.util.Random;
public class Game {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println(welcome());
Pile marbles = new Pile();
Player human = new Player(Player.HUMAN);
Player computer = new Player(Player.COMPUTER);
marbles.setPile();
System.out.println("There are total: " + marbles.getPile()
+ " marbles in the Pile.");
System.out.println("Time for a toin coss to see who goes first!");
System.out.println("Please Select heads(0) or Tails(1): ");
int choice = in.nextInt();
int tossResult = rand.nextInt(2);
boolean playerTurn = false;
boolean computerTurn = false;
if (choice == tossResult) {
System.out.println("You have won the Coin Toss! You will go first!");
human.updateTurn(0);
playerTurn = true;
}
else {
System.out.println("Computer has won the coin toss! Computer will go first");
computer.updateTurn(1);
computerTurn = true;
}
while (marbles.getPile() > 0 && marbles.hasStick()) {
while (playerTurn) {
int removeMarbles = human.makeMove(marbles.getPile());
marbles.reducePile(removeMarbles);
computerTurn = true;
playerTurn = false;
}
while (computerTurn) {
int removeMarbles = computer.makeMove(marbles.getPile());
marbles.reducePile(removeMarbles);
playerTurn = true;
computerTurn = false;
}
}
}
private static String welcome() {
return "Welcome to the Game of Nim";
}
}
So I'm going to take a step back and look at your class diagram.
You have three classes: Pile, Player, and Game. Pile can represent the pile at the center. Game can be the class with the main method that manages everything. And Player? Well, since you're having one Player class for all three (or two) possible states (Human, Dumb, and Smart) it should be pretty easy to implement.
Let's start with Game. It need to contain two instances of Player (human and computer), and an instance of Pile. It also needs to have a loop that goes until the game is over. So let's start to come up with a basic implementation:
Starting with Pile:
private int size;
public Pile(int newSize) {
size = newSize;
}
public boolean takeMarbles(int amount) {
size -= amount;
if (size < 1)
return false;
return true;
}
The constructor is pretty self explanatory. The takeMarbles method is returning false if the player lost, and true if they're still in the game.
Now on to Player:
public static final int HUMAN = 0;
public static final int COMPUTER = 1;
private int type;
public Player(int type) {
this.type = type;
}
Those two static fields may seem a little out of place, but it will come together in a second. On to the Game class:
Pile pile = new Pile(size);
Player human = new Player(Player.HUMAN);
Player computer = new Player(Player.COMPUTER);
Now we have a pile with a certain size, and two players that differ by type. This is how we're using the classes.
Now we need to get the main game loop working. Basically, just add an update() method to Player that depends on it's type (ie prompts for input if player, randomly decides if computer). The update method should return the amount of marbles to take. Then create a loop in the main method in Game. The loop will call update of the player and the computer repeatedly until someone loses (takeMarbles returns false). Then it will break out of the loop and print the output.
This is the basic idea, good luck and feel free to ask more questions!

Java: Variable holder and its value?

I'm having a tough time understanding something from one of my exercises in a book(Complete beginner).
The example code was to make a guessing game with three players and it generates a random int for all three players which has to come out the same as the randomly generated int by the game.
The code contains three classes, but this is the most important one where I have a question. The other two are just GameLauncher class and Player(The one that plays against the other three players) class.
public class GuessGame {
Player p1;
Player p2;
Player p3;
public void startGame(){
p1 = new Player();
p2 = new Player();
p3 = new Player();
int guessp1 = 10;
int guessp2 = 0;
int guessp3 = 0;
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
int targetNumber = (int) (Math.random() * 10);
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();
p3.guess();
guessp1 = p1.number;
System.out.println("Player one has guessed " + guessp1);
guessp2 = p2.number;
System.out.println("Player two has guessed " + guessp2);
guessp3 = p3.number;
System.out.println("Player three has guessed " + guessp3);
if (guessp1 == targetNumber) {
p1isRight = true;
}if (guessp2 == targetNumber){
p2isRight=true;
}if (guessp3 == targetNumber){
p3isRight=true;
}
if (p1isRight||p2isRight||p3isRight){
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("Player three got it right? " + p3isRight);
System.out.println("The game is over.");
break;
}else{
System.out.println("None of you got it right! Try again!");
}
}
}
}
From the above code:
int guessp1 = 10;
int guessp2 = 0;
int guessp3 = 0;
is the one that I don't understand. Originally, all of them are assigned the value 0. I tried to assign 10 to see what would happen, but nothing changed. The game played out just the same.
My question is, what is the significance for the value assigned to a declared integer if any at all? Especially in this situation.
Excluding normal uses like say just printing it or manipulating it with math.
Later in your routine you override the assigned value int the following code lines:
guessp1 = p1.number;
System.out.println("Player one has guessed " + guessp1);
guessp2 = p2.number;
System.out.println("Player two has guessed " + guessp2);
guessp3 = p3.number;
System.out.println("Player three has guessed " + guessp3);
So basically the assigned value is not beeing uset at all, but usually a good practice implies setting a default values to variables so on later use you can determine if a value was assigned or the variable still has its default value.
Defining a default value helps to avoid unexpected situations, In some programming languages created objects which was not assigned or set to null could have any garbage data according to the memory address they reference.
Some use a values like -1 where only positive numbers are expected and catch such a case where no value was assigned by asking if the default value still there or not. In your case the default value is 0.

Rolling two dice

I'm writing a program that is supposed to return the value of rolling two dice. I want the user to be able to select a specified type of die or chose a custom number of sides. So, for example, I chose the triangle die, I would have a 3 sided die.
The variable:
private int die = 1;
private int preselectedSides;
The case in a switch I've made to handle the menu looks like this:
switch(selection)
case 1:
premadeDice(3, 4, 6);
x=1;
break;
The receiving method looks like this:
//premade Dice Selection//
public int premadeDice(int triangle, int rectangle, int cube)
{
String choice;
boolean flag = false;
while (flag == false)
{
System.out.println("Enter in the shape you want your die to be");
System.out.println("A triangle die has 3 sides. If this is what you want, type \"triangle\"");
System.out.println("A rectangle die has 4 sides. If this is what you want, type \"rectangle\"");
System.out.println("A cube die has 6 sides. If this is what you want, type \"cube\"");
choice = sc.next();
if (choice.equalsIgnoreCase("triangle"))
{
System.out.println("You have chosen the triangle die.");
preselectedSides = triangle;
flag = true;
}
else if (choice.equalsIgnoreCase("rectangle"))
{
System.out.println("You have chosen the rectangle die.");
preselectedSides = rectangle;
flag = true;
}
else if (choice.equalsIgnoreCase("cube"))
{
System.out.println("You have chosen the traditonal cube die.");
preselectedSides = cube;
flag = true;
}
else
{
System.out.println("You have not entered in a valid die shape. Try again");
}
}//end while loop
return preselectedSides;
}//end pre-made dice method
I created a getter to get access to that returned value:
//getter for Die
public void getDie()
{
System.out.println(preselectedSides);
}
Call it like this:
test.getDie();
And I get the following output for a cube (or for the other shapes, I keep getting 1 along with the value)
1
6
I've tried finding this logic error but I don't see it. Why does it keep outputting the number one? Ask for clarification if needed.
This seems like an awful lot of code. You can simplify it like so:
public class Die
{
int sides;
//get/set/constructor
...
}
public class DieRoller
{
Die die;
public int roll()
{
Random generator = new Random();
return generator.nextInt(this.die.getSides());
}
}
You can run it like so:
public static void main(String[] args)
{
System.out.println("Number of sides?");
Scanner sc = new Scanner(System.in);
Die currentDie = new Die(sc.nextInt());
System.out.println("Rolling");
DieRoller roller = new DieRoller(currentDie);
int sideRolled = roller.roll();
System.out.println(String.format("You rolled %d on your %d sided die",sideRolled,currentDie.getSides()));
}

Issues with Guessing game java class~

This is a code to play a guessing game that i made, but the problem is that there were several issues which me as a beginner in java are not good at and need some guidance with. along the code there were some errors that i highlighted with an arrow on the side.
import java.util.*;
public class GuessingGame
{
private static Player house;
private static Player player;
private static int wins;
private static int loses;
private String name;
int card1,card2;
private int value;
public void Player(String name){
this.name=name;
card1 = (Integer) null;
card2 = (Integer) null;
}
public void Card(int value){
this.value = value;
}
public int getValue(){
return value;
}
public void acceptDeal(Card card1, Card card2){
Random r = new Random();
int value = r.nextInt(13) + 1;
card1 = new Card(value); <<<<<<<<======= Error 1
value = r.nextInt(13) + 1;
card2 = new Card(value); <<<<<<<<======= Error 2
}
public static void init()
{
house = new Player("House"); <<<<<<<<======= Error 3
player = new Player("Player"); <<<<<<<<======= Error 4
wins = 0;
loses = 0;
}
public static void playGame()
{
Scanner scan = new Scanner(System.in);
char option, playAgain;
int houseHandStrength, playerHandStrength;
System.out.println("Welcome to our card guess 1.0 game!");
System.out.println();
do {
// Deal cards to the house and player.
house.acceptDeal(new Card(houseHandStrength), new Card(houseHandStrength)); <<<<<=== Error 5
player.acceptDeal(new Card(playerHandStrength), new Card(playerHandStrength)); <<<<<=== Error 6
System.out.println(house);
// Determine whether the player wants to play this hand.
do {
System.out.print("Deal cards? (Y/N) ");
option = Character.toLowerCase(scan.next().charAt(0));
}
while (option != 'n' && option != 'y');
if (option == 'y')
{
System.out.println(player);
// Display hand strength of both players.
houseHandStrength = house.getHandStrength(); <<<<<=== Error 7
playerHandStrength = player.getHandStrength(); <<<<<=== Error 8
System.out.println("The dealer's hand strength is: " + houseHandStrength);
System.out.println("Your hand strength is: " + playerHandStrength);
System.out.println();
// If the player has a stronger hand.
if (player.getHandStrength() > house.getHandStrength())
{
System.out.println("** You won the hand! **");
wins++;
}
else {
System.out.println("The house wins this round!");
loses++;
}
}
// Display the win/lose statistics.
System.out.println("Current wins: " + wins);
System.out.println("Current loses: " + loses);
// Prompt whether the user wants to play again.
do {
System.out.print("Would you like to play again? (Y/N) ");
playAgain = Character.toLowerCase(scan.next().charAt(0));
}
while (playAgain != 'n' && playAgain != 'y');
System.out.println();
System.out.println("*******************************************************");
}
while (playAgain == 'y');
System.out.println();
System.out.println("Thank you for playing!");
}
public static void main(String[] args)
{
init();
playGame();
}
}
First of all welcome to StackOverflow. It's nice to see that you have found and used the homework tag. Keep in mind that for people to be able to help you, you need to give more information. What do you mean by error, what happens when you run the code etc
regarding the errors you get, it appears as you haven't really defined classes Card and Player, what you have there in your code are two methods GuessingGame.Card() and GuessingGame.Player() in your GuessingGame class. Change them to inner (or outer) classes and it should be fine ;)
Maybe you need to import your other classes at the top?
The problems seem to be only in your own classes, what do the program output say about the errors?
public void Player(String name)...
and
public void Card(int value)...
should be classes right? Declare them as classes in another file and include them to the main file.
In your previous Question card1 and card2 were of type Card. That was right, now you have changed this and now it is wrong.
You seemed to have bunched up your code. You've combined the Player, Card and Game classes. I don't have a Java compiler handy, but what you're looking to do is to break out the three models.
Error 1-6 were a result of trying to instantiate new objects when the class doesn't even exist. Error 7-8 were a result of trying to call a methods on the same.
import java.util.*;
class Player {
int card1, card2;
private String name;
public void Player(String name){
this.name=name;
card1 = (Integer) null;
card2 = (Integer) null;
}
public void acceptDeal(Card card1, Card card2){
Random r = new Random();
int value = r.nextInt(13) + 1;
card1 = new Card(value); <<<<<<<<======= Error 1
value = r.nextInt(13) + 1;
card2 = new Card(value); <<<<<<<<======= Error 2
}
}
class Card {
private int value;
public void Card(int value){
this.value = value;
}
public int getValue(){
return value;
}
}
public class GuessingGame
{
private static Player house;
private static Player player;
private static int wins;
private static int loses;
public static void init()
{
house = new Player("House"); <<<<<<<<======= Error 3
player = new Player("Player"); <<<<<<<<======= Error 4
wins = 0;
loses = 0;
}
public static void playGame()
{
Scanner scan = new Scanner(System.in);
char option, playAgain;
int houseHandStrength, playerHandStrength;
System.out.println("Welcome to our card guess 1.0 game!");
System.out.println();
do {
// Deal cards to the house and player.
house.acceptDeal(new Card(houseHandStrength), new Card(houseHandStrength)); <<<<<=== Error 5
player.acceptDeal(new Card(playerHandStrength), new Card(playerHandStrength)); <<<<<=== Error 6
System.out.println(house);
// Determine whether the player wants to play this hand.
do {
System.out.print("Deal cards? (Y/N) ");
option = Character.toLowerCase(scan.next().charAt(0));
}
while (option != 'n' && option != 'y');
if (option == 'y')
{
System.out.println(player);
// Display hand strength of both players.
houseHandStrength = house.getHandStrength(); <<<<<=== Error 7
playerHandStrength = player.getHandStrength(); <<<<<=== Error 8
System.out.println("The dealer's hand strength is: " + houseHandStrength);
System.out.println("Your hand strength is: " + playerHandStrength);
System.out.println();
// If the player has a stronger hand.
if (player.getHandStrength() > house.getHandStrength())
{
System.out.println("** You won the hand! **");
wins++;
}
else {
System.out.println("The house wins this round!");
loses++;
}
}
// Display the win/lose statistics.
System.out.println("Current wins: " + wins);
System.out.println("Current loses: " + loses);
// Prompt whether the user wants to play again.
do {
System.out.print("Would you like to play again? (Y/N) ");
playAgain = Character.toLowerCase(scan.next().charAt(0));
}
while (playAgain != 'n' && playAgain != 'y');
System.out.println();
System.out.println("*******************************************************");
}
while (playAgain == 'y');
System.out.println();
System.out.println("Thank you for playing!");
}
public static void main(String[] args)
{
init();
playGame();
}
}

Categories

Resources