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();
}
}
Related
So my code runs fine and all; no problems, or atleast I think it doesn't have any; I need to add two final things: first one is a way to make a beep sound (think I have to use toolkit, actionListener, etc) and the other thing, is a way to print the current random number the program generates (something like a toString). I've tried my professor's methods for the beep sound and nothing, so now I'm here. Thanks in advance.
Tried some methods from my professors code but nothing.
//Interface
package edu.pupr.LottoGame;
public interface Ask {
public void ask();
}
//Class
package edu.pupr.LottoGame;
import java.util.Random;
import javax.swing.JOptionPane;
public class theLotto {
//VARIABLE
public int values;
//OVERLOAD CONSTRUCTOR
public theLotto(int values) {
this.values = values;
}
//MUTATOR
public void setValues(int values) {
this.values = values;
}
//ACCESSOR
public int getValues() {
return values;
}
//ANONYMOUS CLASS
public void start() {
Ask ak = new Ask() {
public void ask() {
//ANONYMOUS VARIABLES USED
String input = null;
int reply;
int randomNum;
//BEGINNING OF FIRST DO-WHILE
do {
//INPUT OF USER : 4 DIGITS
input = JOptionPane.showInputDialog("Plese enter 4 digits (1000-9999)");
values = Integer.parseInt(input);
}while(values < 1000 || values > 9999);
//ENDING OF FIRST DO WHILE
//RANDOM NUMBER GENERATOR
Random rn = new Random();
randomNum = 1000 + rn.nextInt(10000 - 1000);
//DETERMINES IF THE USER WON OR LOST
if(values == randomNum)
JOptionPane.showMessageDialog(null, "You Won! The num: " + randomNum);
else
JOptionPane.showMessageDialog(null, "You Lost! The wining num was: " + randomNum);
//BEGINNING OF SECOND DO-WHILE
do {
//WANNA PLAY AGAIN PANEL
reply = JOptionPane.showConfirmDialog(null, "Continue?", null, JOptionPane.YES_NO_OPTION);
//IF OPTION IS YES
if (reply == JOptionPane.YES_OPTION) {
//BEGINNIG OF THIRD DO-WHILE
do {
//INPUT OF USER : 4 DIGITS
input = JOptionPane.showInputDialog("Plese enter 4 digits (1000-9999)");
values = Integer.parseInt(input);
}while(values < 1000 || values > 9999);
//END OF THIRD DO-WHILE
//RANDOM NUMBER GENERATOR
Random rn2 = new Random();
randomNum = 1000 + rn2.nextInt(10000 - 1000);
//DETERMINES IF THE USER WON OR LOST
if(values == randomNum)
JOptionPane.showMessageDialog(null, "You Won! The num: " + randomNum);
else
JOptionPane.showMessageDialog(null, "You Lost! The wining num was: " + randomNum);
}
//IF OPTION IS NO
else {
JOptionPane.showMessageDialog(null, "GOODBYE");
System.exit(0);
}
}while(reply != JOptionPane.NO_OPTION);
//END OF SECOND DO-WHILE
}
};
//PART OF ANONYMOUS
ak.ask();
}
}
//Class Driver
package edu.pupr.LottoGame;
public class theLottoDriver {
public static void main(String [] args) {
theLotto lt = new theLotto(0);
lt.start();
}
}
Ouput should be something like this:
Enter Number: 3267
09/07/2019 09:50:23:
throw #1: 4392
throw #2: 8391
You lost !!!
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
So what I have here is a fully functioning roulette game in java, running on eclipse. I want to improve it beyond What it was supposed to be by allowing the user to specify how many players they want to be in the same game, as opposed to the two hardcoded players. currently I put a way to set individual names for player 1 and 2 so me and a friend could play but I feel this would make it more universal. The goal is to take the code I have now and learn how to take a specified number, throw it into a loop to generate player objects (each with their own name) and have the program still function.
I have three classes, the Player class witch holds my constructors and payment methods, and getName() getMoney() methods as well. the Roulette class witch is the main method for the program where this loop to add player objects should be added. and the Wheel class where the randomly generated ball position is held and so forth.
here is the first class:
import java.util.Scanner;
//************************************************************************
// Class Player represents one roulette player.
//************************************************************************
public class Player
{
private int bet, money, betType, number, betNet;
#SuppressWarnings("unused")
private static int houseWins;
private String name;
private Scanner scan = new Scanner(System.in);
//=====================================================================
// The Player constructor sets up name and initial available money.
//=====================================================================
public Player (String playerName, int initialMoney)
{
name = playerName;
money = initialMoney;
} // constructor Player
//=====================================================================
// Returns this player's name.
//=====================================================================
public String getName()
{
return name;
} // method getName
//=====================================================================
// Returns this player's current available money.
//=====================================================================
public int getMoney()
{
return money;
} // method getMoney
//=====================================================================
// returns the net bets for that player
//=====================================================================
public int getNet()
{
return betNet;
}
//=====================================================================
// Prompts the user and reads betting information.
//=====================================================================
#SuppressWarnings("static-access")
public void makeBet(Wheel Wheel)
{
Scanner scan = new Scanner(System.in);
System.out.print("How much do you want to bet " + name + "? : ");
bet = scan.nextInt();
if(bet>=money)
{
System.out.println("im going all in!");
bet= money;
money = money-bet;
}
else
{
money = money-bet;
}
Wheel.betOptions();
System.out.println("Choose your bet type: ");
betType = scan.nextInt();
if(betType == 3){
System.out.println("your'e betting on: a number");
while(true){
System.out.println("Please enter the number you "
+ "wish to bet on from 1 to 36: ");
number = scan.nextInt();
if(number <1 || number > 36)
{
System.out.println("This Number is not in "
+ "the desired range.");
}
else
{
break;
}
}
}
}
// method makeBet
//=====================================================================
// Determines if the player wants to play again.
//=====================================================================
public boolean playAgain(Scanner scan)
{
String answer;
System.out.println (name + " Play again [Y/N]? ");
answer = scan.nextLine();
return (answer.equals("y") || answer.equals("Y"));
}
// method playAgain
public void payment(Wheel Wheel2)
{
int winnings = Wheel2.payoff(bet, betType, number);
money += winnings;
if(winnings > 0)
{
betNet += (winnings-bet);
Roulette.setHouseWins(-(winnings-bet));
}
else
{
betNet -= bet;
Roulette.setHouseWins((bet));
}
// =========================================================
// if player runs out of money.
// =========================================================
if(money < 1)
{
Scanner scan = new Scanner(System.in);
System.out.println(name + ", you're out of money. "
+ "Do you want to bet more? [Y/N] ");
String answer= scan.nextLine();
if(answer.equals("y") || answer.equals("Y"))
{
if (betNet>-200)
{
System.out.println("You bought back in for 100");
money +=100;
}
else {
System.out.println("Sorry buddy, your cutt off from the credit line.");
money = 0;
}
}
}
//setHouseWins(betNet);
System.out.println(" Testing to see how much is "
+ "betNet keeping track of: " + betNet);
}
}
Then here is the Wheel class:
//************************************************************************
// Class Wheel represents a roulette wheel and its operations. Its
// data and methods are static because there is only one wheel.
//************************************************************************
public class Wheel
{
// public name constants -- accessible to others
public final static int BLACK = 0; // even numbers
public final static int RED = 1; // odd numbers
public final static int GREEN = 2; // 00 OR 0
public final static int NUMBER = 3; // number bet
public final static int MIN_NUM = 1; // smallest number to bet
public final static int MAX_NUM = 36; // largest number to bet
// private name constants -- internal use only
private final static int MAX_POSITIONS = 38; // number of positions on wheel
private final static int NUMBER_PAYOFF = 35; // payoff for number bet
private final static int COLOR_PAYOFF = 2; // payoff for color bet
// private variables -- internal use only
private static int ballPosition; // 00, 0, 1 .. 36
private static int color; // GREEN, RED, OR BLACK
//=====================================================================
// Presents welcome message
//=====================================================================
public static void welcomeMessage()
{
System.out.println("Welcome to a simple version of roulette game.");
System.out.println("You can place a bet on black, red, or a number.");
System.out.println("A color bet is paid " + COLOR_PAYOFF + " the bet amount.");
System.out.println("A number bet is paid " + NUMBER_PAYOFF + " the bet amount.");
System.out.println("Have fun and good luck!\n");
}
//=====================================================================
// Presents betting options
//=====================================================================
public static void betOptions()
{
System.out.println("Betting Options:");
System.out.println(" 1. Bet on black");
System.out.println(" 2. Bet on red");
System.out.println(" 3. Bet on a number between " + MIN_NUM +
" and " + MAX_NUM);
System.out.println();
}
//=====================================================================
// method spins the wheel
//=====================================================================
public int spin()
{
ballPosition= (int)(Math.random() * MAX_POSITIONS + 1);;
if(ballPosition < 37)
{
if(ballPosition % 2 == 0)
{
color = BLACK;
}
else
{
color = RED;
}
}
else
{
color = GREEN;
}
System.out.print("the Result is: "+ ballPosition
+ " and color is: ");
if (color == BLACK)
{
System.out.println("BLACK.");
}
else if (color == RED)
{
System.out.println("RED.");
}
else
{
System.out.println("GREEN.");
}
return ballPosition;
}
//=====================================================================
// calculates the payoff
//=====================================================================
public int payoff( int bet, int betType, int number)
{
if (color == GREEN)
{
return 0;
}
else if (betType == 1 && color == BLACK)
{
return bet * COLOR_PAYOFF;
}
else if (betType == 2 && color == RED)
{
return bet * COLOR_PAYOFF;
}
else if (betType == 3 && number == ballPosition)
{
return bet * NUMBER_PAYOFF;
} else return 0;
}
}
and Finally the main method roulette class:
import java.util.*;
//************************************************************************
// Class Roulette contains the main driver for a roulette betting game.
//************************************************************************
public class Roulette
{
private static int houseMoney=0;
//=====================================================================
// Contains the main processing loop for the roulette game.
//=====================================================================
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String name1 = "jane"; String name2 = "don";
Wheel wl1 = new Wheel();
System.out.println("please enter a name for player 1: ");
name1 = scan.nextLine();
System.out.println("please enter a name for player 2: ");
name2 = scan.nextLine();
Player player1 = new Player (name1, 100); // $100 to start for Jane
Player player2 = new Player (name2, 100); // $100 to start for Dave
boolean bl1 = true;
boolean bl2 = true;
Wheel.welcomeMessage();
while (bl1 || bl2)
{
System.out.println ("Money available for " + player1.getName()
+ ": " + player1.getMoney());
if(bl1)player1.makeBet(wl1);
System.out.println ("Money available for " + player2.getName()
+ ": " + player2.getMoney());
if(bl2)player2.makeBet(wl1);
wl1.spin();
if(bl1 == true)
{
//initiate the payment
player1.payment(wl1);
System.out.println ("Money available for " + player1.getName() + ": "
+ player1.getMoney());
// check weather play the game again
if(!player1.playAgain(scan))
{
bl1 = false;
System.out.println(player1.getName()+" total wins/losses: "
+ player1.getNet());
}
}
// check the boolean value
if(bl2 == true)
{
//initiate the payment
player2.payment(wl1);
System.out.println ("Money available for " +
player2.getName() + ": " + player2.getMoney());
// check weather play the game again
if(!player2.playAgain(scan))
{
bl2 = false;
System.out.println(player2.getName()+ " total wins/losses: "
+ player2.getNet());
}
}
}
System.out.println();
System.out.printf("House %s: $%d", houseMoney > 0 ? "Wins" : "Losses", houseMoney);
System.out.println();
System.out.println ("Game over! Thanks for playing.");
}
public static void setHouseWins(int Winnings)
{
houseMoney += Winnings;
}
}
ive tried a few different ways to generate the player objects but I think the real issue is coming up with a boolean object for each respective player that wants to quit to be able to stop playing. please help a guy out! (Ps: feel free to use this program as a basis for your own roulette games as it does function quite well as is.)
The goal is to create a two player dice throwing game with text menus through console. I have 3 classes, Game, Player and Dice. The player class just has string player name field and int player score field The dice class has the RNG code but most of the game is in the game class.
When starting a game I name two players (text taken from user) and create two player objects. I can call the "roll dice" method which returns the score from one round of the game, but how do I add that score to the field already defined in the player objects?
There is supposed to be one object per player but I don't seem to be able to refer to each individual object. Is there a problem with having those objects created in a different method but of the same class as the method thats trying to increment the player score?
import java.util.Scanner;
public class Game
{
// instance variables - replace the example below with your own
private int x;
/**
* Constructor for objects of class Game
*/
public Game()
{
// initialise instance variables
x = 0;
}
public void menu()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to My Dice-and-Roll Game!");
System.out.println("=================================");
System.out.println("(1) Start a New Game");
System.out.println("(2) Play One Round");
System.out.println("(3) Who is leading now?");
System.out.println("(4) Display Game Help");
System.out.println("(5) Exit Game");
System.out.println("(6) Choose an option:");
int selection = scanner.nextInt();
switch (selection) {
case 1:
// Perform "original number" case.
nameplayers();
playround();
break;
case 2:
// Perform "encrypt number" case.
System.out.println("(2) ");
break;
case 3:
// Perform "decrypt number" case.
System.out.println("(3) ");
break;
case 4:
// Perform "quit" case.
System.out.println("(4) ");
break;
default:
// The user input an unexpected choice.
}
}
public void nameplayers()
{
String namep1;
String namep2;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the name of player 1: ");
namep1 = scanner.next( );
Player P1 = new Player();
P1.setName(namep1);
System.out.print("Enter the name of player 2: ");
namep2 = scanner.next( );
Player P2 = new Player();
P2.setName(namep2);
}
public void rolldice()
{
int dice1;
int dice2;
int rollTotal;
// put your code here
dice1 = (int)(Math.random()*6) + 1;
dice2 = (int)(Math.random()*6) + 1;
if(dice1 == dice2){
rollTotal = ((dice1 + dice2) *2);
}
else {
rollTotal = (dice1 + dice2);
}
System.out.println(" has rolled a " + dice1 + " and " + dice2 + " which totals " + rollTotal + " points");
P1.addScore(rollTotal);
}
public void playround()
{
String namep1;
String namep2;
Scanner scanner = new Scanner(System.in);
System.out.println("The dice are thrown!");
try{
Thread.sleep(2000);//2000ms = 2s
}catch(InterruptedException ex){
}
System.out.println("..");
try{
Thread.sleep(2000);//2000ms = 2s
}catch(InterruptedException ex){
}
System.out.println(" ..");
try{
Thread.sleep(2000);//2000ms = 2s
}catch(InterruptedException ex){
}
System.out.println(" :");
try{
Thread.sleep(2000);//2000ms = 2s
}catch(InterruptedException ex){
}
System.out.println(" ..");
try{
Thread.sleep(2000);//2000ms = 2s
}catch(InterruptedException ex){
}
rolldice();
}
}
import java.util.Scanner;
public class Player
{
// the name of the player
private String playerName;
// the current score of the player
private int playerScore;
/**
* Constructor for objects of class Player
*/
public Player()
{
String playerName = "";
int playerScore = 0;
}
public void setName(String newName)
{
// put your code here
playerName = newName;
System.out.println("Player name set as " +
newName);
}
public void addScore(int addScore)
{
// put your code here
playerScore = playerScore + addScore;
}
}
You need to have a reference to the Players' outside of the method. Because you declarePlayer playerinside thenamePlayers()` method, as soon as you leave the method (method scope) the objects are no longer visible / referenced, and become available to be garbage Collected.
Define the Players as local variables to your Game class:
public class Game
{
Player player1;
Player player2;
}
Then in your namePlayers() method, just create and set the players:
P1 = new Player();
P1.setName(namep1);
System.out.print("Enter the name of player 2: ");
namep2 = scanner.next( );
P2 = new Player();
P2.setName(namep2);
The most object oriented way to do it would be to write a method that updates the private variable. Something like:
public void updateScore(int score) {
this.x = x + score;
{
You would call this method on your player object like:
player1.updateScore(resultPlayer1);
player2.updateScore(resultPlayer2);
I'm creating a high/low guessing game as part of a study assignment, and the part im stuck at is getting the amount of guesses returned to the main method. We have specifically been told that the main method has to print the number of guesses, while the method "playGame" actually does the playing.
There's more to the code, a method called giveReponse that checks if the number is correct or too high/low, but it works as intended. I get "Cannot find symbol" when trying to print how many guesses it took to complete the game.
If it wasn't so important to print it in the main method I'd print the amount in the method playGame, but thats a no-go. What am I doing wrong?
The code looks like this:
public class HiLo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to classic guessing game of high/low!");
String difficulty = scan.next();
if (difficulty.equals("easy")) {
playGame(10);
} else if (difficulty.equals("medium")) {
playGame(100);
} else if (difficulty.equals("hard")) {
playGame(1000);
}
System.out.println("You won in" + guesses + "attempts.");
}//EndsMain
public static int playGame(int maxNumber) {
Scanner scan = new Scanner(System.in);
int rannr = (int)(Math.random() * maxNumber) +1;
int answer = rannr;
int guess = 0;
int guesses = 0;
System.out.println("Game is starting...");
do {
guess = scan.nextInt();
guesses ++;
giveResponse(answer, guess);
if (answer == guess) {
break;
}
} while (answer != guess);
return guesses;
} //Ends playGame
Your method playGame( ) is returning a value but since is not assigned to no variable, those returns are getting lost...
additional to that it looks like the code is not complete:
this statement is not going to let you compile:
System.out.println("You won in" + guesses + "attempts.");
because the only guesses variable I see in there is scoped in the playGame method....
do instead something like:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to classic guessing game of high/low!");
int guesses = 0;
String difficulty = scan.next();
if (difficulty.equals("easy")) {
guesses = playGame(10);
} else if (difficulty.equals("medium")) {
guesses = playGame(100);
} else if (difficulty.equals("hard")) {
guesses = playGame(1000);
}
The problem is at:
System.out.println("You won in" + guesses + "attempts.");
Since the variable guesses is not defined in the main method, the compiler doesn't know what you are referencing to with that symbol.
But since playGame() returns the number of guesses, I'd recommend something like this:
if (difficulty.equals("easy")) {
System.out.println("You won in" +playGame(10)+ "attempts.");
} else if (difficulty.equals("medium")) {
System.out.println("You won in" +playGame(100)+ "attempts.");
} else if (difficulty.equals("hard")) {
System.out.println("You won in" +playGame(1000)+ "attempts.");
}
Here's a solution that shows how easy it would be to restrict guesses. Not much extra effort or thought:
package games;
import java.util.Random;
import java.util.Scanner;
/**
* HiLo guessing game
* Created by Michael
* Creation date 4/9/2016.
* #link https://stackoverflow.com/questions/36522303/java-creating-hi-low-game-using-multiple-methods-stuck-at-returning-no-of-gu
*/
public class HiLo {
public static void main(String [] args) {
int maxValue = (args.length > 0) ? Integer.parseInt(args[0]) : 100;
int maxGuesses = (args.length > 1) ? Integer.parseInt(args[1]) : 5;
Scanner scanner = new Scanner(System.in);
String answer = "Y";
do {
play(scanner, maxValue, maxGuesses);
System.out.println("Play again? [Y/N]: ");
answer = scanner.next();
System.out.println(String.format("You answered %s; let's play again!", answer));
} while ("Y".equalsIgnoreCase(answer));
}
private static void play(Scanner scanner, int maxValue, int maxGuesses) {
int value = new Random().nextInt(maxValue) + 1;
int numGuesses = 0;
boolean match = false;
do {
System.out.println(String.format("Guess a value between 1 and %d: ", maxValue));
int guess = Integer.parseInt(scanner.next());
if (guess < value) {
System.out.println(String.format("Too low; guess again. (%d guesses left)", (maxGuesses-numGuesses-1)));
} else if (guess > value) {
System.out.println(String.format("Too high; guess again (%d guesses left)", (maxGuesses-numGuesses-1)));
} else {
match = true;
System.out.println(String.format("You got it right in %d guesses! ", numGuesses+1));
break;
}
} while (!match && ++numGuesses < maxGuesses);
if (!match) {
System.out.println(String.format("The correct answer was %d; you're only allowed %d guesses. Better luck next time!", value, maxGuesses));
}
}
}