There are a couple of tasks I need to complete and I need a little guidance.
First, I have to have the T command which allows the player to take the item that is in the current room they are in. The items for each room are in their respective Locale arrays. By using itemPresent it takes the item that the player1 current room is originally set to and the room is not updated throughout the game, instead it is updated within the move() method. I wanted to use roomData[2] to get the item that way, but since I can't take a variable from another method, I am unable to do this. So, how would I be able to take the item from the current room?
Second, I need to remove the item from the room once it is taken so that an item can't be taken twice.
Third, I would have to add this taken item to the player's inventory which I tried to set up using an ArrayList. I am not sure how to set up the code so that I can take the item I just found and add it to the inventory.
Thank you for all help!!
Here is my main class:
import java.util.Scanner;
import java.util.ArrayList;
public class GameEngine {
static Scanner userInput = new Scanner(System.in);
static String[] playerInfo = {"playerName"};
static Player player1 = new Player("playerName", null, 0, 0);
//Welcome Message
public static void displayIntro(){
System.out.println("\tWelcome to Power Outage!");
System.out.println("=================================================");
System.out.print("\tLet's start by creating your character.\n\tWhat is your name? ");
//Will read what name is entered and return it
playerInfo[0]= userInput.nextLine();
System.out.println("\tHello, " +playerInfo[0]+ ". Let's start the game! \n\tPress any key to begin.");
System.out.print("=================================================");
//Will move to next line when key is pressed
userInput.nextLine();
System.out.print("\tYou wake up in your bedroom. \n\tThe power has gone out and it is completely dark. \n"
+"\tYou must find your way to the basement to start the generator. \n\tMove in any direction by typing, "
+ "'N', 'S', 'E', or 'W'.\n\tType 'H' at any time for help and 'Q' "
+ "to quit the game. Good luck!\n\tPress any key.");
userInput.nextLine();
}
//Locations {roomName, description, item}
static String[][] Locale ={
{"bedroom","You see the outline of a bed with your childhood stuffed bear on it.","map"},
{"hallway","A carpeted floor and long pictured walls lie ahead of you.",null},
{"kitchen","The shining surface of your stove reflects the pale moonlight coming in the window over the sink.","battery"},
{"bathroom","You find yourself standing in front of a mirror, looking back at yourself.","flashlight"},
{"living room","You stub your toe on the sofa in the room, almost falling right into the TV.","battery"},
{"dining room","You bump the china cabinet which holds your expensive dishes and silverware.","key"},
{"office","The blinking light from the monitor on your desk can be seen in the dark",null},
{"library","The smell of old books surrounds you.","battery"},
{"basement","You reach the top of some stairs and upon descending down, you find the large metal generator.",null},
};
//Matrix for rooms
static int[][] roomMap = {
// N,E,S,W
{6,1,-1,-1}, //Bedroom (room 0)
{4,2,3,0}, //Hallway (room 1)
{-1,-1,5,1}, //Kitchen (room 2)
{1,-1,-1,-1}, //Bathroom (room 3)
{-1,7,1,-1}, //Living Room (room 4)
{2,-1,-1,-1}, //Dining Room (room 5)
{-1,-1,0,-1}, //Office (room 6)
{8,-1,-1,4}, //Library (room 7)
{-1,-1,7,-1} //Basement (room 8)
};
//Items
private String paperMap = "map";
private String key = "key";
private String flashlight = "flashlight";
private String battery = "battery";
static int currentLocation = player1.currentRoom;
//take method
//String[] currentInventory = {};
// player1.inventory = currentInventory;
/*
private static int[] itemNames = {"map","key","flashlight","battery"};
for(int i=0; i<itemNames.length; i++){
if(itemNames[i].equals("map")){
}
}
*/
//inventory
ArrayList<String> inventory = new ArrayList<String>();
//static String[] itemPresent = roomData[2];
//move method
private static String[] dirNames = {"North", "East", "South", "West"};
private static void move(int dir) {
int dest = roomMap[currentLocation][dir];
if (dest >= 0 && dest != 8) {
System.out.println("=================================================");
System.out.println("\tYou have moved " + dirNames[dir]);
currentLocation = dest;
String[] roomData = Locale[currentLocation];
System.out.println("\tYou are in the "+roomData[0]+".");
System.out.println("\t"+roomData[1]);
String itemPresent = roomData[2];
}
else if (dest == 8){
System.out.println("\tCongratulations!! You have found the basement and turned on the generator! \n\tYou have won the game!");
System.out.println("\tTHANKS FOR PLAYING!!!!!!");
System.out.println("\tCopyright 2016 \n\n");
stillPlaying = false;
}
else {
System.out.println("\tThere is no exit that way, please try again.");
}
}
//All possible responses to keys pressed
public static void pressedKey(){
while(stillPlaying){
String response = userInput.nextLine();
if(player1.currentRoom != 8 && !response.equalsIgnoreCase("Q") ){
if(response.equalsIgnoreCase("M")){
//only print if the player has the map
System.out.println("Here is your map: \n\n\t\t\tbasement\n\noffice\t living room\tlibrary\n\nbedroom\t hallway\tkitchen\n\n\t bathroom \tdining room");
break;
}
else if(response.equalsIgnoreCase("T")){
// check if there is an item in the player's current room
if( itemPresent != null){
// if there is, then add it to the player's inventory and remove it from the locale
System.out.println("You have gained: " +itemPresent+ ". This adds the item to your inventory and you get 5 points added to your score!");
//add to inventory--- player1.inventory itemPresent;
player1.score = +5;
//remove item from the locale
}
else{
System.out.println("There is no item to take in this room.");
}
}
else if(response.equalsIgnoreCase("H")){
System.out.println("To move, type 'N' for North, 'S' for South, 'W' for West, or 'E' for East."
+"\nTry to navigate to the basement to turn on the generator."
+"\nTake an item from the room you are in by pressing 'T'."
+"\nCheck your inventory by pressing 'I'."
+ "\nYou can type 'Q' at any time to quit the game.\n");
break;
}
else if(response.equalsIgnoreCase("I")){
System.out.println("These are the items in your inventory: "+player1.inventory+".");
}
else if(response.equalsIgnoreCase("N")){
move(0);
break;
}
else if(response.equalsIgnoreCase("E")){
move(1);
break;
}
else if(response.equalsIgnoreCase("S")){
move(2);
break;
}
else if(response.equalsIgnoreCase("W")){
move(3);
break;
}
else{
System.out.println("\tInvalid command!");
}
}//End of if statement
else if(response.equalsIgnoreCase("Q")){
System.out.println("Thanks for playing!\n\n");
stillPlaying = false;
}
}//End of while
}//End of pressedKey method
static boolean stillPlaying = true; //When this is true, the game continues to run
public static void main(String[] args) {
displayIntro();
System.out.println("=================================================");
System.out.println("\tYou are in the bedroom.");
while(stillPlaying){//This makes the game continue to loop
System.out.println("=================================================");
System.out.println("\tMove in any direction.");
pressedKey();
} //End of while
} //End of main
} //End of class
This is my Player class
public class Player {
//import java.util.Scanner;
//Player class must have name, location, inventory, and score
//Instead of array of descriptions, use array of Locale objects
private String playerName;
public String inventory;
public int score;
public int currentRoom;
public Player(String playerName, String inventory, int score, int currentRoom){
this.playerName = playerName;
this.inventory = inventory;
this.score = 0;
this.currentRoom = currentRoom;
}
}
This is my Locale class
public class Locale {
//Locale must have name, description, and item
private String roomName;
private String description;
private String item;
public Locale(String roomName, String description, String item){
this.roomName = roomName;
this.description = description;
this.item = item;
}
}
Related
I am working on a text-based adventure game and need some help handling the IndexOutOfBounds exception on the getUserRoomChoice() function. I have an index of 3 on the menu so when the user enters a number > 3, it throws that exception. I tried using a try-catch on the line where it prompts the user to "Select a Number" but it is not catching it.
Here is my main class:
import java.util.Scanner;
public class Game {
private static Room library, throne, study, kitchen;
private static Room currentLocation;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
initialSetupGame();
String reply;
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? Yes/No: ");
reply = input.nextLine().toLowerCase();
} while ('y' == reply.charAt(0));
goodbye();
}
public static void initialSetupGame() {
// Instantiate room objects of type Room
library = new Room("Library");
throne = new Room("Throne");
study = new Room("Study");
kitchen = new Room("Kitchen");
// Connect the objects to each other
library.addConnectedRoom(throne);
library.addConnectedRoom(study);
library.addConnectedRoom(kitchen);
throne.addConnectedRoom(library);
throne.addConnectedRoom(study);
throne.addConnectedRoom(kitchen);
study.addConnectedRoom(library);
study.addConnectedRoom(throne);
study.addConnectedRoom(kitchen);
kitchen.addConnectedRoom(library);
kitchen.addConnectedRoom(study);
kitchen.addConnectedRoom(throne);
// Welcome message
System.out.println("Welcome to Aether Paradise, "
+ "a game where you can explore"
+ " the the majestic hidden rooms of Aether.");
// Prompt user for a name
Scanner input = new Scanner(System.in);
System.out.print("\nBefore we begin, what is your name? ");
String playerName = input.nextLine();
System.out.print("\n" + playerName +"? Ah yes. The Grand Warden told us"
+ " to expect you. Nice to meet you, " + playerName + "."
+ "\nMy name is King, a member of the Guardian Aethelorian 12"
+ " who protect the sacred rooms of Aether."
+ "\nAs you hold the Warden's signet ring, you have permission"
+ " to enter.\n\nAre you ready to enter? ");
String response = input.nextLine().toLowerCase();
if ('n' == response.charAt(0)) {
System.out.println("Very well then. Goodbye.");
System.exit(0);
}
if ('y' == response.charAt(0)) {
System.out.println("\nA shimmering blue portal appeared! You leap "
+ "inside it and your consciousness slowly fades...");
}
else {
System.out.println("Invalid input. Please try again.");
System.exit(1);
}
// Set the player to start in the library
currentLocation = library;
System.out.print("\nYou have spawned at the library.");
System.out.println(currentLocation.getDescription());
}
public static void printNextRooms() {
// Lists room objects as menu items
System.out.println("Where would you like to go next?");
currentLocation.printListOfNamesOfConnectedRooms();
}
// How to handle the exception when input > index?
public static int getUserRoomChoice() {
Scanner input = new Scanner(System.in);
System.out.print("(Select a number): ");
int choice = input.nextInt();
return choice - 1;
}
public static Room getNextRoom(int index) {
return currentLocation.getConnectedRoom(index);
}
public static void updateRoom(Room newRoom) {
currentLocation = newRoom;
System.out.println(currentLocation.getDescription());
}
public static void goodbye() {
System.out.println("You walk back to the spawn point and jump into"
+ "the portal... \n\nThank you for exploring the hidden rooms "
+ "of Aether Paradise. Until next time.");
}
}
Room Class
import java.util.ArrayList;
public class Room {
// Instance variables
private String name;
private String description;
private ArrayList<Room> connectedRooms;
// Overloaded Constructor
public Room(String roomName) {
this.name = roomName;
this.description = "";
connectedRooms = new ArrayList<>();
}
// Overloaded Constructor
public Room(String roomName, String roomDescription) {
this.name = roomName;
this.description = roomDescription;
connectedRooms = new ArrayList<>();
}
// Get room name
public String getName() {
return name;
}
// Get room description
public String getDescription() {
return description;
}
// Add connected room to the array list
public void addConnectedRoom(Room connectedRoom) {
connectedRooms.add(connectedRoom);
}
// Get the connected room from the linked array
public Room getConnectedRoom(int index) {
if (index > connectedRooms.size()) {
try {
return connectedRooms.get(index);
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
return connectedRooms.get(index);
}
// Get the number of rooms
public int getNumberOfConnectedRooms() {
return connectedRooms.size();
}
// Print the connected rooms to the console
public void printListOfNamesOfConnectedRooms() {
for(int index = 0; index < connectedRooms.size(); index++) {
Room r = connectedRooms.get(index);
String n = r.getName();
System.out.println((index + 1) + ". " + n);
}
}
}
You have to use try-catch in function call of getNextRoom().
Because getNextRoom(nextRoomIndex) is causing the exception. You have to put those two statements in try block.
Change this to
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
this
try{
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
} catch(Exception e){
System.out.println("print something");
}
You must have a closer look to the piece of code, where you try to access the list (or array). That is the part, where the exception is thrown, not when the user enters it. There you have to check, if the given index is larger than the size of your list.
if( index >= list.size()) {
// handle error / print message for user
} else {
// continue normaly
}
In your case, it would probably be in the method getConnectedRoom(int index) in class Room.
Where is your try/catch block for the specific part? anyway, you can use IndexOutOfBound or Custome Exception for it.
1.create a custom Exception Class
class RoomeNotFoundException extends RuntimeException
{
public RoomeNotFoundException(String msg)
{
super(msg);
}
}
add try/catch block for the specific part
public class Game
{
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
if(nextRoomeIndex>3)
{
throw new RoomNotFoundException("No Rooms Available");
}else{
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? Yes/No: ");
reply = input.nextLine().toLowerCase();
}
} while ('y' == reply.charAt(0));
}
Or you can use IndexOutOfBoundException instead of RoomNotFoundException
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.)
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
My assignment is to try and create a card game and I'm stuck at the point where I am trying to display the cards in a jframe. I have a Displayable instance and a Displayble hand deck and card which implements this. I'm stuck at what to put inside the display method that they have to override and also what I should put in the jframe class/jpanel. Any help is much appreciated thanks a lot.
public interface Displayable {
public void display(Graphics g, int x, int y);
}
Example of one of the displayable classes.
public class DisplayableCard extends Card implements Displayable {
Graphics g;
String filename = "\\images\\classic-cards\\7.png";
Image image = new ImageIcon(getClass().getResource(filename)).getImage();
#Override
public void display(Graphics G, int x,int y)
{
}
}
We got given this code to use and told to- "Test your new classes by creating a simple subclass of JFrame, which contains an instance of CardGamePanel. Simply construct and add an appropriate Displayable object to the CardGamePanel instance to test each Displayable"
public class CardGamePanel extends JPanel{
private Displayable theItem;
private int x, y;
#Override
public void paint(Graphics g) {
if (theItem != null)
{
theItem.display(g, x, y);
}
}
public void setItem(Displayable item, int x, int y) {
theItem = item;
this.x = x;
this.y = x;
}
}
So I tried this:
public class simple extends JFrame
{
CardGamePanel c = new CardGamePanel();
Displayable d;
DisplayableDeck d1 = new DisplayableDeck();
}
public class mainclass {
public static void main(String args[])
{
DisplayableDeck d1 = new DisplayableDeck();
simple s1 = new simple();
s1.c.setItem(d1, 50, 50); // like this?
}
}
Any help much appreciated :)
You can try this program
public class HighLow {
public static void main(String[] args) {
System.out.println("This program lets you play the simple card game,");
System.out.println("HighLow. A card is dealt from a deck of cards.");
System.out.println("You have to predict whether the next card will be");
System.out.println("higher or lower. Your score in the game is the");
System.out.println("number of correct predictions you make before");
System.out.println("you guess wrong.");
System.out.println();
int gamesPlayed = 0; // Number of games user has played.
int sumOfScores = 0; // The sum of all the scores from
// all the games played.
double averageScore; // Average score, computed by dividing
// sumOfScores by gamesPlayed.
boolean playAgain; // Record user's response when user is
// asked whether he wants to play
// another game.
do {
int scoreThisGame; // Score for one game.
scoreThisGame = play(); // Play the game and get the score.
sumOfScores += scoreThisGame;
gamesPlayed++;
TextIO.put("Play again? ");
playAgain = TextIO.getlnBoolean();
} while (playAgain);
averageScore = ((double)sumOfScores) / gamesPlayed;
System.out.println();
System.out.println("You played " + gamesPlayed + " games.");
System.out.printf("Your average score was %1.3f.\n", averageScore);
} // end main()
/**
* Lets the user play one game of HighLow, and returns the
* user's score on that game. The score is the number of
* correct guesses that the user makes.
*/
private static int play() {
Deck deck = new Deck(); // Get a new deck of cards, and
// store a reference to it in
// the variable, deck.
Card currentCard; // The current card, which the user sees.
Card nextCard; // The next card in the deck. The user tries
// to predict whether this is higher or lower
// than the current card.
int correctGuesses ; // The number of correct predictions the
// user has made. At the end of the game,
// this will be the user's score.
char guess; // The user's guess. 'H' if the user predicts that
// the next card will be higher, 'L' if the user
// predicts that it will be lower.
deck.shuffle(); // Shuffle the deck into a random order before
// starting the game.
correctGuesses = 0;
currentCard = deck.dealCard();
TextIO.putln("The first card is the " + currentCard);
while (true) { // Loop ends when user's prediction is wrong.
/* Get the user's prediction, 'H' or 'L' (or 'h' or 'l'). */
TextIO.put("Will the next card be higher (H) or lower (L)? ");
do {
guess = TextIO.getlnChar();
guess = Character.toUpperCase(guess);
if (guess != 'H' && guess != 'L')
TextIO.put("Please respond with H or L: ");
} while (guess != 'H' && guess != 'L');
/* Get the next card and show it to the user. */
nextCard = deck.dealCard();
TextIO.putln("The next card is " + nextCard);
/* Check the user's prediction. */
if (nextCard.getValue() == currentCard.getValue()) {
TextIO.putln("The value is the same as the previous card.");
TextIO.putln("You lose on ties. Sorry!");
break; // End the game.
}
else if (nextCard.getValue() > currentCard.getValue()) {
if (guess == 'H') {
TextIO.putln("Your prediction was correct.");
correctGuesses++;
}
else {
TextIO.putln("Your prediction was incorrect.");
break; // End the game.
}
}
else { // nextCard is lower
if (guess == 'L') {
TextIO.putln("Your prediction was correct.");
correctGuesses++;
}
else {
TextIO.putln("Your prediction was incorrect.");
break; // End the game.
}
}
/* To set up for the next iteration of the loop, the nextCard
becomes the currentCard, since the currentCard has to be
the card that the user sees, and the nextCard will be
set to the next card in the deck after the user makes
his prediction. */
currentCard = nextCard;
TextIO.putln();
TextIO.putln("The card is " + currentCard);
} // end of while loop
TextIO.putln();
TextIO.putln("The game is over.");
TextIO.putln("You made " + correctGuesses
+ " correct predictions.");
TextIO.putln();
return correctGuesses;
} // end play()
} // end class
You can try out the game in this applet, which simulates the program:
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();
}
}