Adding to an object field - java

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);

Related

How do I use variables in one method into another method?

So I was wondering if someone could show me how I can call/reference a variable from one method into another method. For example,
public static void main(String[] args)
{
System.out.println("Welcome to the game of sticks!");
playerNames();
coinToss();
}
public static void playerNames()
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter player 1's name: ");
String p1 = input.nextLine();
System.out.print("Enter player 2's name: ");
String p2 = input.nextLine();
System.out.println();
System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}
public static void coinToss()
{
System.out.println("A coin toss will decide who goes first:");
System.out.println();
Random rand = new Random();
int result = rand.nextInt(2);
result = rand.nextInt(2);
if(result == 0)
{
System.out.println(p1 + " goes first!");
}
else
{
System.out.println(p2 + " goes first!");
}
}
I want to use p1 and p2 from playerNames() inside of coinToss() so I can simply announce who goes first, but I just can't figure out how to call the variables.
My question is not really different compared to others, however I was unable to understand the answers others were given. Once I posted this I got the answer from a bunch of kind people :)
I'm assuming you are new to Java, because it seems you aren't familiar with the concept of fields (i.e. you can put variables outside methods).
public class YourClass {
static String p1;
static String p2;
public static void main(String[] args)
{
System.out.println("Welcome to the game of sticks!");
playerNames();
coinToss();
}
public static void playerNames()
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter player 1's name: ");
p1 = input.nextLine();
System.out.print("Enter player 2's name: ");
p2 = input.nextLine();
System.out.println();
System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}
public static void coinToss()
{
System.out.println("A coin toss will decide who goes first:");
System.out.println();
Random rand = new Random();
int result = rand.nextInt(2);
result = rand.nextInt(2);
if(result == 0)
{
System.out.println(p1 + " goes first!");
}
else
{
System.out.println(p2 + " goes first!");
}
}
}
what you are searching for is called instance variables, check this out.
https://www.tutorialspoint.com/java/java_variable_types.htm
All I had to do was create the instance/static variables outside! Like this:
static String name1;
static String name2;
It was very easy. Thanks everyone for your help!

Trying to add a user inputted number of players to a consol based roulette game

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.)

How to add different instances of the same object to a LinkedList in Java?

I'm designing a shop system here, and it is mainly a media shop, containing items like video games, DVDs and CDs. The issue I am having is that I want to store different instances of the same object, in this case VideoGames, into a linked list. It seems to work, but when I output the List, it only outputs the last item entered into the list and repeats itself for the amount of objects which were supposed to be in the list.
I understand that it is a lot of code to look through, but any help would be greatly appreciaed.
Here is the code for the addVideoGame class:
import java.util.*;
import java.io.*;
public class addVideoGame extends VideoGames implements java.io.Serializable{
public static VideoGames game = new VideoGames();
public static VideoGames eGame = new VideoGames();
public static LinkedList <VideoGames> games = new LinkedList<>();
private static int vgChoice = 0;
public static int vgCount = 0;
public static int vgAmount = 0;
public static void vgMenu(){
IBIO.output("1: Add a new videogame to the list.");
IBIO.output("2: View the contents of the list.");
IBIO.output("3: Save the contents of the list to the local area.");
IBIO.output("4: Load in data from a local file.");
IBIO.output("5: Return to the main menu.");
vgChoice = IBIO.inputInt("Make your choice: ");
if(vgChoice == 1){
vgAmount = IBIO.inputInt("How many games would you like to add to the database?: ");
for(int x = 0; x < vgAmount; x = x + 1){
VideoGames vg = new VideoGames();
vg.setTitle(IBIO.inputString("Enter the title of the game: "));
vg.setPublisher(IBIO.inputString("Enter the publisher of the game: "));
vg.setDeveloper(IBIO.inputString("Enter the developer of the game: "));
vg.setAgeRating(IBIO.inputInt("Enter the age rating of the game: "));
vg.setGenre(IBIO.inputString("Enter the genre of the game: "));
vg.setQuantity(IBIO.inputInt("Enter the available quantity of the game: "));
game = vg;
games.add(vg);
IBIO.output(" ");
}
vgMenu();
} else if(vgChoice == 2){
IBIO.output("Current amount of games in the list: " + games.size());
System.out.println(Arrays.toString(games.toArray()));
vgMenu();
} else if(vgChoice == 3){
try{
FileOutputStream fileOut = new FileOutputStream("I:\\IB\\Computer Science\\TheStore\\games.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(game);
out.close();
fileOut.close();
IBIO.output("Data has been saved to: I:\\IB\\Computer Science\\TheStore\\games.txt");
vgMenu();
} catch(IOException i){
i.printStackTrace();
}
} else if(vgChoice == 4){
eGame = null;
for(int x = 0; x < games.size(); x = x + 1){
try{
FileInputStream fileIn = new FileInputStream("I:\\IB\\Computer Science\\TheStore\\games.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
eGame = (VideoGames) in.readObject();
in.close();
fileIn.close();
} catch (IOException i){
i.printStackTrace();
return;
} catch(ClassNotFoundException c){
IBIO.output("VideoGames class not found");
c.printStackTrace();;
return;
}
IBIO.output("Object Details: " + eGame.toString());
vgMenu();
}
} else if(vgChoice == 5){
IBIO.output("Returning to main menu: ");
AccessMenus.adminMenu();
}
}
}
If anyone needs them, here are the two interface classes used to navigate the program:
public class TheStore {
static String password; //Variable created to hold and check the value of password against the correct value.
public static boolean privilege = false; //Variable created to distinguish the difference between a normal user and a user with administrator privileges.
public static void main(String[] args) {
IBIO.output("Welcome to The Store!");
IBIO.output("Please make sure that you enter the correct password for your given privileges.");
password = IBIO.inputString("Enter password: ");
if(password.equalsIgnoreCase("admin")){ //Checks the entered value against the correct value.
privilege = true; //Sets global boolean value to true, so that admin access is granted.
IBIO.output(" ");
AccessMenus.adminMenu();//If password is correct, loads admin menu.
} else if(password.equalsIgnoreCase("user")){
privilege = false; //Keeps admin access off, so that unauthorised changes cannot be made.
IBIO.output(" ");
AccessMenus.userMenu();//If correct, loads user menu.
} else {
IBIO.output("The password is incorrect. Exiting program.");
System.exit(1); //If an incorrect password is entered, the program will close.
} //close else
}//close main
}//close class TheStore
And the second one:
public class AccessMenus{
public static int choice;//Variable which will hold the value, which corresponds to an action depending on what value is entered.
public AccessMenus(){ //Null argument constructor, to set values to 0.
AccessMenus.choice = 0;
}
public AccessMenus(int c){ //Single argument constructor.
AccessMenus.choice = c;
}
public static void userMenu(){
IBIO.output("1: Sell a product.");
IBIO.output("2: Register a customer in the Loyalty programme.");
IBIO.output("3: Stock check.");
IBIO.output("4: Log out.");
IBIO.output(" ");
IBIO.output("Please make your choice: ");
choice = IBIO.inputInt();
if(choice == 1){
//Go to Sales class.
} else if(choice == 2){
//Go to CustomerRegister class.
} else if(choice == 3){
//Open the StockCheck class.
} else if(choice == 4){
IBIO.output("Logging out.");
System.exit(1);
} else {
IBIO.output("Invalid choice. Returning to menu.");
userMenu(); //If the value entered does not correspond to any action, the program will treat it as invalid and return to the menu.
}//close else
}//close userMenu
public static void adminMenu(){
IBIO.output("1: Sell a product.");
IBIO.output("2: Go to the specific object menus.");
IBIO.output("3: Stock check.");
IBIO.output("4: Order more stock.");
IBIO.output("5: Register a customer in the Loyalty programme.");
IBIO.output("6: Check Loyalty members.");
IBIO.output("7: Create databases.");
IBIO.output("8: Log out.");
IBIO.output(" ");
IBIO.output("Please make your choice: ");
choice = IBIO.inputInt();
if(choice == 1){
//Go to Sales class.
} else if(choice == 2){
int createChoice = 0;
IBIO.output("1: Video Games.");
IBIO.output("2: DVD.");
IBIO.output("3: CD.");
createChoice = IBIO.inputInt("Enter choice: ");
if(createChoice == 1){
addVideoGame.vgMenu();
} else if(createChoice == 2){
//Go to addDVD class.
} else if(createChoice == 3){
//Go to addCD class.
} else {
IBIO.output("Invalid input.");
adminMenu();
}
} else if(choice == 3){
//Go to StockCheck class.
} else if(choice == 4){
//Go to StockOrder class.
} else if(choice == 5){
//Go to CustomerRegister class.
} else if(choice == 6){
//Go to LoyaltyCheck class.
} else if(choice == 7){
//Go to DatabaseCreation class.
} else if(choice == 8){
IBIO.output("Logging out.");
System.exit(1);
} else {
IBIO.output("Invalid input. Returning to menu.");
adminMenu();
} //end else
}//close AdminMenu
}//close AccessMenus
Also, here is the VideoGames object class, containing things like the accessor and mutator methods and primary fields:
public class VideoGames implements java.io.Serializable {
//Instance variables
public static String title;
public static int ageRating;
public static String genre;
public static String publisher;
public static String developer;
public static int quantity;
public VideoGames(){ //null argument constructor
VideoGames.title = null;
VideoGames.ageRating = 0;
VideoGames.genre = null;
VideoGames.publisher = null;
VideoGames.developer = null;
VideoGames.quantity = 0;
}//end VideoGames null argument constructor
public VideoGames(String t, int aG, String g, String p, String d, int q){ //6-argument constructor
VideoGames.title = t;
VideoGames.ageRating = aG;
VideoGames.genre = g;
VideoGames.publisher = p;
VideoGames.developer = d;
VideoGames.quantity = q;
}//end VideoGames 6-arguement constructor
public VideoGames(VideoGames game){
game = new VideoGames();
}
#Override
public String toString(){
return "\nTitle: " + title + " " + "\nPublisher: " + publisher + " " + "\nDeveloper: " + developer + " " + "\nAge Rating: " + ageRating + " " + "\nGenre: " + genre + " " + "\nQuantity: " + quantity + "\n ";
}
//Accessor and Mutator methods
public static String getTitle(){
return title;
}
public static void setTitle(String t){
title = t;
}
public static int getAgeRating(){
return ageRating;
}
public static void setAgeRating(int ag){
ageRating = ag;
}
public static String getGenre(){
return genre;
}
public static void setGenre(String g){
genre = g;
}
public static String getPublisher(){
return publisher;
}
public static void setPublisher(String p){
publisher = p;
}
public static void setDeveloper(String d){
developer = d;
}
public static String getDeveloper(){
return developer;
}
public static void setQuantity(int q){
quantity = q;
}
public static int getQuantity(){
return quantity;
}//end method setDeveloper
}//end class VideoGames
Again, any help would be greatly appreciated.
There is too much code for me to properly go through but it sounds like (and a quick scan seemed to confirm) you are only creating one VideoGames object. Whenever you change any fields within that object it changes the field in that single object.
You then add that same VideoGames object multiple times to the list, but these are all separate references to the same object.
Instead VideoGames should be called VideoGame and contain the data for one game you should then create a new VideoGame() and set it up each time you add one to the list.
Remember the list only contains references to objects, not objects themselves.
Each VideoGames object is like a house on a street. At the moment you build one house and keep painting the door on that house different colours instead of building multiple houses and painting the door on each house a different colour.
Your list is just a list of addresses when you add the same house 4 times the list just repeats the same address.
So you were doing:
Build a house in plot 1
Paint house door blue
Write down plot 1 in a list
Paint house door green
Add plot 1 to the list again
Paint house door red
Add plot 1 to the list again
Now you go down the list, you see three entries - but when you go and look at the door colour they all say red.
The field of VideoGames class are all static. Static field belong to Class and only one memory space in method area of JVM. When you execute for loop:
VideoGames vg = new VideoGames();
you create one VideoGames instance, but when you execute set method:
vg.setTitle(IBIO.inputString("Enter the title of the game: "));
vg.setPublisher(IBIO.inputString("Enter the publisher of the game: "));
vg.setDeveloper(IBIO.inputString("Enter the developer of the game: "));
vg.setAgeRating(IBIO.inputInt("Enter the age rating of the game: "));
vg.setGenre(IBIO.inputString("Enter the genre of the game: "));
vg.setQuantity(IBIO.inputInt("Enter the available quantity of the game: "));
the data you receive will be set to the static field in method area. The value you set previous will be covered by the value you set following. When you print the value of list. You will get value from the static field in method area.
So,
but when I output the List, it only outputs the last item entered into the list and repeats itself for the amount of objects which were supposed to be in the list.
Hope to help you.
Sorry for my poor English.
You are using static members in your VideoGames -class.
The value of this affects all objects, e.g.
public class X {
public static int y;X() { }
public
}
X x1 = new X();
x1.y = 1;
X x2 = new X();
x2.y = 2;
System.out.println("x1.y" + x1.y); // 2
System.out.println("x2.y" + x2.y); // 2

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();
}
}

I need to restructure this class without the use of instance variables

So I'm doing a TUI and this was my first iteration.
package bulb.classes;
import java.util.Scanner;
import java.util.ArrayList;
public class RoomTUI {
private ArrayList<Room> rooms;
Scanner scan = new Scanner (System.in);
private int userNumber;
private String userAnswer;
public void run() {
rooms = new ArrayList<Room>();
introduction();
userNumber = 0;
options();
while(userNumber < 5) {
if(userNumber == 1) {
newRoom();
}
if(userNumber == 2) {
addBulbToRoom();
}
if(userNumber == 3) {
clickAllBulbsInRoom();
}
if(userNumber == 4) {
printDescriptionOfBulbs();
}
}
System.out.println("Goodbye");
}
public int getUserInt(String aString) {
System.out.println(aString);
userAnswer = scan.nextLine();
userNumber = Integer.parseInt(userAnswer);
return userNumber;
}
public void displayRooms() {
System.out.println("Possible rooms to choose from.");
String tempString = "";
int roomIndex = 0;
for (int i = 0; i < rooms.size(); i++) {
tempString = tempString + "Room " + roomIndex++ + ": " + rooms.get(i).getDescription() + "\n";
}
System.out.println(tempString);
}
public void introduction() {
System.out.println("Welcome! With this program you can make rooms and design and place the light bulbs for each room you create.");
}
public void options() {
System.out.println("1 : Create a new Room");
System.out.println("2 : Add a bulb to an existing room");
System.out.println("3 : Click all of the bulbs in a particular room");
System.out.println("4 : Display a description of all bulbs in a particular room");
System.out.println("5 : Quit");
getUserInt("What would you like to do?");
}
public void newRoom() {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
rooms.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
public void addBulbToRoom() {
displayRooms();
System.out.println("Which room do you want the bulb in?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println("Please enter the blub's color.");
String color = scan.nextLine();
System.out.println("Please enter the blub's increment amount.");
String incrementS = scan.nextLine();
int incrementI = Integer.parseInt(incrementS);
ThreeWayBulb aBulb = new ThreeWayBulb(color, incrementI);
rooms.get(choiceNumber).addBulb(aBulb);
System.out.println("A " + color + " bulb with and increment of " + incrementI + " was added.");
options();
}
public void clickAllBulbsInRoom() {
displayRooms();
System.out.println("Which room do you want the bulbs clicked?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
rooms.get(choiceNumber).clickAllBulbs();
System.out.println("The bulbs in " + rooms.get(choiceNumber).getDescription() + " have been clicked.");
options();
}
public void printDescriptionOfBulbs() {
displayRooms();
System.out.println("Please enter a room number.");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println(rooms.get(choiceNumber).getDescription() + " with " + rooms.get(choiceNumber).returnSize() + " bulbs: " + "\n" + rooms.get(choiceNumber).toString());
options();
}
}
My instructor wants me to do this without instance variables He said if a method needs the ArrayList that I should make it a parameter and have no instance variables in my TUI. I can't for the life of me figure out how to do that. Also, making it static work fly either. Thanks for any help you can give.
He wants you to declare the ArrayList from a central location (such as the main thread) and then pass it as an argument to the functions that use it. This way if you were to take methods and put them in different classes then it wouldn't break because they're not dependent on this class.
For example if we take your newRoom class:
public void newRoom(List<Room> roomList) {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
roomList.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
EDIT: The easiest way to achieve this is to probably move the declaration of rooms to within your run method. Now for each location in the code that reports "unknown variable rooms" you can modify the function to take an ArrayList as a parameter.
Well, eliminating userNumber and userAnswer as members is trivial; their usage is very localized.
For the list, just pass it around after creating it in your main loop.
The scanner is used multiple places; it could also be passed around, I suppose.

Categories

Resources