Heading
Program for Java class, supposed to be the game Pass the Pigs, tried everything, but cant get the special case marked by //FIXME to execute. Below is the code i have written. Any advice welcome on where i went wrong. I know there is a way to make it shorter using a for-loop, but i need to get this program working properly before trying to get it looking sleek. Thank you.
package ch07labx;
import java.util.Random;
import java.util.Scanner;
public class PassThePigs {
//names of pieces
public static final String SIDER_NO_DOT = "Sider(no dot)";
public static final String SIDER_DOT = "Sider(dot)";
public static final String TROTTER = "Trotter";
public static final String RAZORBACK = "Razorback";
public static final String SNOUTER = "Snouter";
public static final String LEANING_JOWLER = "Leaning Jowler";
//score for piece landings
public static final int SIDER_NO_DOT_SCORE = 0;
public static final int SIDER_DOT_SCORE = 0;
public static final int TROTTER_SCORE = 5;
public static final int RAZORBACK_SCORE = 5;
public static final int SNOUTER_SCORE = 10;
public static final int LEANING_JOWLER_SCORE = 15;
//odds of landing
public static final int SIDER_NO_DOT_PROB = 33;
public static final int SIDER_DOT_PROB = 66;
public static final int TROTTER_PROB = 76;
public static final int RAZORBACK_PROB = 96;
public static final int SNOUTER_PROB = 99;
public static final int LEANING_JOWLER_PROB = 100;
private static Scanner scnr = new Scanner(System.in);
public static void main(String[] args) {
String pigRollOne = null;
String pigRollTwo = null;
int wholeTurnScore = 0;
String userInput = null;
do {
int rollScore = 0;
Random randGen = new Random();
int rollOne = randGen.nextInt(100) + 1;
int rollTwo = randGen.nextInt(100) + 1;
int rollOneScore = 0;
int rollTwoScore = 0;
//rollOne outcomes
if (rollOne <= SIDER_NO_DOT_PROB) {
pigRollOne = SIDER_NO_DOT;
rollOneScore = SIDER_NO_DOT_SCORE;
} else if (rollOne <= SIDER_DOT_PROB) {
pigRollOne = SIDER_DOT;
rollOneScore = SIDER_DOT_SCORE;
} else if (rollOne <= TROTTER_PROB) {
pigRollOne = TROTTER;
rollOneScore = TROTTER_SCORE;
} else if (rollOne <= RAZORBACK_PROB) {
pigRollOne = RAZORBACK;
rollOneScore = RAZORBACK_SCORE;
} else if (rollOne <= SNOUTER_PROB) {
pigRollOne = SNOUTER;
rollOneScore = SNOUTER_SCORE;
} else if (rollOne == LEANING_JOWLER_PROB) {
pigRollOne = LEANING_JOWLER;
rollOneScore = LEANING_JOWLER_SCORE;
}
//rollTwo outcomes
if (rollTwo <= SIDER_NO_DOT_PROB) {
pigRollTwo = SIDER_NO_DOT;
rollTwoScore = SIDER_NO_DOT_SCORE;
} else if (rollTwo <= SIDER_DOT_PROB) {
pigRollTwo = SIDER_DOT;
rollTwoScore = SIDER_DOT_SCORE;
} else if (rollTwo <= TROTTER_PROB) {
pigRollTwo = TROTTER;
rollTwoScore = TROTTER_SCORE;
} else if (rollTwo <= RAZORBACK_PROB) {
pigRollTwo = RAZORBACK;
rollTwoScore = RAZORBACK_SCORE;
} else if (rollTwo <= SNOUTER_PROB) {
pigRollTwo = SNOUTER;
rollTwoScore = SNOUTER_SCORE;
} else if (rollTwo == LEANING_JOWLER_PROB) {
pigRollTwo = LEANING_JOWLER;
rollTwoScore = LEANING_JOWLER_SCORE;
}
rollScore = rollOneScore + rollTwoScore;
//special cases
if ((pigRollOne.equals(SIDER_DOT) && pigRollTwo.equals(SIDER_NO_DOT)) ||
(pigRollOne.equals(SIDER_NO_DOT) && pigRollTwo.equals(SIDER_DOT))){
rollScore = 0;
wholeTurnScore = 0;
System.out.print("Rolling... " + pigRollOne +
" & " + pigRollTwo);
System.out.println();
System.out.print("this roll: " + rollScore);
System.out.println();
System.out.print("this turn: " + wholeTurnScore);
System.out.println();
System.out.println("Pig out!");
break;
}
if ((pigRollOne.equals(SIDER_DOT) && pigRollTwo.equals(SIDER_DOT)) ||
(pigRollOne.equals(SIDER_NO_DOT) && pigRollTwo.equals(SIDER_NO_DOT))){
rollScore = 1; //FIXME
}
if (pigRollOne.equals(pigRollTwo)) {
rollScore = 2 * (rollOneScore + rollTwoScore);
}
wholeTurnScore += rollScore;
//screen outputs
System.out.print("Rolling... " + pigRollOne +
" & " + pigRollTwo);
System.out.println();
System.out.print("this roll: " + rollScore);
System.out.println();
System.out.print("this turn: " + wholeTurnScore);
System.out.println();
System.out.print("Roll again (y/n)? ");
userInput = scnr.next();
if(userInput.charAt(0) == 'n'){
break;
}
}while (userInput.charAt(0) == 'y');
}
}
Related
I'm creating an UNO project and am a bit confused about how to assign the drivers to my DiscardPile class.
Thank you in advance for any answers you may give.
Sincerely,
Jayda M
I've asked my fellow students for assistance and have scoured the internet for anything that could be helpful with no luck. My professor isn't helpful at all haha
This is the full code for the Driver.java file. If you need me to give you any of the others I have no problem doing so.
package unoGame;
import java.util.Random;
//import java.util.Collections;
public class Driver {
public static unoDeck theDeck = new unoDeck();
public static PlayerHand[] thePlayers;
public static DiscardPile dp = new DiscardPile();
public static int nextPlayer;
public static Random getRandom = new Random();
public static void main(String[] args) {
// TODO Auto-generated method stub
thePlayers = new PlayerHand[3];
thePlayers[0] = new PlayerHand("name 1");
thePlayers[1] = new PlayerHand("name 2");
thePlayers[2] = new PlayerHand("name 3");
theDeck.shuffle();
System.out.println("Here is the Deck: " + theDeck);
System.out.println(" Welcome to UNO! ");
if (dp.isEmpty()) {
System.out.println(" Discard is Empty ");
}
else {
System.out.println(" Not Empty ");
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < thePlayers.length; j++) {
thePlayers[j].addCard(theDeck.deal());
}
}
nextPlayer = 0;
showPlayers();
dp.addCard(theDeck.deal());
while (checkForWin() == false) {
findNextPlayer();
if (theDeck.isEmpty()) {
theDeck.replenish(dp.clear());
}
playerTurn();
}
System.out.println(thePlayers[nextPlayer], getName() + " Wins!")
}
public static void showPlayers() {
for (PlayerHand p : thePlayers)
System.out.println(p);
}
public static boolean checkForWin() {
if (p.isWin()) {
win = true;
}
return win;
}
public static void findNextPlayer() {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
if(dp.getTopCard().getValue()=="SK") {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
}
if(dp.getTopCard().getValue() == "D2") {
for(int i = 0; i <= 1; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if(dp.getTopCard().getValue() == "W4") {
for(int i = 0; i <= 3; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if(dp.getTopCard().getValue() == "RV") {
for(int i = 0; i < thePlayers.length / 2; i++) {
PlayerHand rev = thePlayers[i];
thePlayers[i] = thePlayers[thePlayers.length - i -1];
rev = thePlayers[thePlayers.length - i -1];
if(nextPlayer == 0) {
nextPlayer = 0;
}
if(nextPlayer == 2) {
nextPlayer = 1;
}
}
nextPlayer++;
}
}
public static void playerTurn() {
if (thePlayers[nextPlayer].hasMatch(dp.getTopCard())) {
System.out.println(thePlayers[nextPlayer].getName() + " has a match!");
unoCard c = thePlayers[nextPlayer].playCard(dp.getTopCard());
dp.addCard(c);
if(c.getValue().equals("W")) {
c.setColor(theDeck.newColor());
}
if(c.getValue().equals("W4")) {
c.setColor(theDeck.newColor());
}
System.out.println(thePlayers[nextPlayer].getName() + " played a: " dp.getTopCard());
System.out.println(thePlayers[nextPlayer]);
}
else {
unoCard c = theDeck.deal();
thePlayers[nextPlayer]c.addCard(c);
System.out.println(thePlayers[nextPlayer].getName() + " drew a: " + c);
}
}
}
There are errors are on these lines of code: 46, 50, 57, 58, 60, 106 and 111. Most of them are saying they're undefined, and I'm unsure of where to do so amongst my files. I'm expecting the Driver to run the game as a whole, so because it's gone wack I can't run the build properly. If you need more information to work with, I'll gladly give it to you!
EDIT:
The lines and/or words where the errors are taking place have asterisks around them
The error descriptions with their corresponding lines
The printed console error after running Driver. Hopefully this works for the Reproducible Example required :)
Here is your Driver class with compilation problems fixed. I suggest you compare it with your current code in order to see what I changed.
I also needed to add method replenish() in class unoDeck because it didn't exist and is called from class Driver. Right now that method does nothing. As I said, I only added it in order to fix the compilation error.
package unoGame;
import java.util.Random;
public class Driver {
public static unoDeck theDeck = new unoDeck();
public static PlayerHand[] thePlayers;
public static DiscardPile dp = new DiscardPile();
public static int nextPlayer;
public static Random getRandom = new Random();
public static void main(String[] args) {
thePlayers = new PlayerHand[3];
thePlayers[0] = new PlayerHand("name 1");
thePlayers[1] = new PlayerHand("name 2");
thePlayers[2] = new PlayerHand("name 3");
theDeck.shuffle();
System.out.println("Here is the Deck: " + theDeck);
System.out.println(" Welcome to UNO! ");
if (dp.isEmpty()) {
System.out.println(" Discard is Empty ");
}
else {
System.out.println(" Not Empty ");
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < thePlayers.length; j++) {
thePlayers[j].addCard(theDeck.deal());
}
}
nextPlayer = 0;
showPlayers();
dp.addCard(theDeck.deal());
while (checkForWin() == false) {
findNextPlayer();
if (theDeck.isEmpty()) {
theDeck.replenish(dp.clear());
}
playerTurn();
}
System.out.println(thePlayers[nextPlayer].getName() + " Wins!");
}
public static void showPlayers() {
for (PlayerHand p : thePlayers)
System.out.println(p);
}
public static boolean checkForWin() {
boolean win = false;
if (thePlayers[nextPlayer].isWin()) {
win = true;
}
return win;
}
public static void findNextPlayer() {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
if (dp.getTopCard().getValue() == "SK") {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
}
if (dp.getTopCard().getValue() == "D2") {
for (int i = 0; i <= 1; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if (dp.getTopCard().getValue() == "W4") {
for (int i = 0; i <= 3; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if (dp.getTopCard().getValue() == "RV") {
for (int i = 0; i < thePlayers.length / 2; i++) {
PlayerHand rev = thePlayers[i];
thePlayers[i] = thePlayers[thePlayers.length - i - 1];
rev = thePlayers[thePlayers.length - i - 1];
if (nextPlayer == 0) {
nextPlayer = 0;
}
if (nextPlayer == 2) {
nextPlayer = 1;
}
}
nextPlayer++;
}
}
public static void playerTurn() {
if (thePlayers[nextPlayer].hasMatch(dp.getTopCard())) {
System.out.println(thePlayers[nextPlayer].getName() + " has a match!");
unoCard c = thePlayers[nextPlayer].playCard(dp.getTopCard());
dp.addCard(c);
if(c.getValue().equals("W")) {
c.setColor(theDeck.newColor());
}
if(c.getValue().equals("W4")) {
c.setColor(theDeck.newColor());
}
System.out.println(thePlayers[nextPlayer].getName() + " played a: " + dp.getTopCard());
System.out.println(thePlayers[nextPlayer]);
}
else {
unoCard c = theDeck.deal();
thePlayers[nextPlayer].addCard(c);
System.out.println(thePlayers[nextPlayer].getName() + " drew a: " + c);
}
}
}
I've created a program with an object called CarlysCatering. I'm trying to sort the CarlysCatering objects by number of guests.
I've tried using a bubble sort but I get an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CarlysCatering[] event = new CarlysCatering[100];
event[0] = new CarlysCatering(10, "A547", "6874714145", 0);
event[1] = new CarlysCatering(100, "B527", "6874874945", 2);
event[2] = new CarlysCatering(50, "C546", "6874785145", 3);
event[3] = new CarlysCatering(40, "L577", "6874321485", 1);
event[4] = new CarlysCatering(70, "A111", "6874714145", 4);
event[5] = new CarlysCatering(90, "K222", "6874974855", 2);
event[6] = new CarlysCatering(11, "F798", "6875555555", 3);
event[7] = new CarlysCatering(17, "T696", "6474763898", 0);
//SORT
int selection = 0;
do {
System.out.println("1 - sort by eventID. 2 - sort by number of guests. 3 - sort by event type. 4 - quit");
selection = input.nextInt();
input.nextLine();
if(selection == 1) {
}
if(selection == 2) {
int n = event.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (event[j].getGuests() > event[j + 1].getGuests()) {
// swap arr[j+1] and arr[i]
CarlysCatering temp = event[j];
event[j] = event[j + 1];
event[j + 1] = temp;
}
}
}
}
} while (selection != 4);
//Print totals
event[0].getTotals(); event[1].getTotals(); event[2].getTotals(); event[3].getTotals(); event[4].getTotals(); event[5].getTotals(); event[6].getTotals(); event[7].getTotals();
}
////////////////////////////////////////////////////// STATIC METHODS //////////////////////////////////////////////////////////////////////
}
public class CarlysCatering {
public static final int PRICE_PER_GUEST_HIGH = 35;
public static final int PRICE_PER_GUEST_LOW = 32;
public static final int CUTOFF_VALUE_LARGE = 49;
private int guests;
private int totalPrice;
private String eventID;
private String phoneNumber;
private String eventType;
private boolean largeEvent;
///////////////////////////////////////////////////// CONSTRUCTORS //////////////////////////////////////////////////////////////////
CarlysCatering() {
this.guests = 0;
this.eventID = "A000";
this.phoneNumber = "0000000000";
}
CarlysCatering(int guests, String eventID, String phoneNumber, int eventType) {
this.guests = guests;
this.eventID = eventID;
//Phone Number formatting
String phoneNumber2 = "";
int count = 0;
for(int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0,3) + ") " + phoneNumber2.substring(3,6) + "-" + phoneNumber2.substring(6,10);
this.phoneNumber = phoneNumber3;
}
//Event type formatting
final String[] eventString = new String[5];
eventString[0] = "wedding"; eventString[1] = "baptism"; eventString[2] = "birthday"; eventString[3] = "corporate"; eventString[4] = "other";
if(eventType > -1 && eventType < 5) {
this.eventType = eventString[eventType];
} else {
this.eventType = eventString[4];
}
}
///////////////////////////////////////////////////////// SETTERS AND GETTERS /////////////////////////////////////////////////
//Setters
public void setEventID(String eventID) {
this.eventID = eventID;
}
public void setGuests(int guests) {
this.guests = guests;
}
public void setPhoneNumber(String phoneNumber) {
String phoneNumber2 = "";
int count = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0, 3) + ") " + phoneNumber2.substring(3, 6) + "-" + phoneNumber2.substring(6, 10);
this.phoneNumber = phoneNumber3;
}
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
//Getters
public int getTotalPrice() {
return totalPrice;
}
public int getGuests() {
return guests;
}
public String getEventID() {
return eventID;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getEventType() {
return eventType;
}
/////////////////////////////////////////////////////// ADDITIONAL METHODS ///////////////////////////////////////////////////////////////////
public void isLargeEvent() {
if (this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
System.out.println("Yes this is a large event.");
} else {
largeEvent = false;
System.out.println("This is not a large event");
}
}
public void getTotals() {
boolean largeEvent = false;
if(this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
this.totalPrice = this.guests * PRICE_PER_GUEST_HIGH;
} else {
largeEvent = false;
this.totalPrice = this.guests * PRICE_PER_GUEST_LOW;
}
System.out.println("The number of guests attending event " + this.eventID + " " + this.eventType + " is: " + this.guests + ". The total price is $" + this.totalPrice);
System.out.println("Large event: " + largeEvent);
System.out.println("The phone number on file is " + this.phoneNumber);
}
// Static methods
public static void showMotto() {
System.out.println("*****Carly's makes the food that makes it a party.*****");
}
}
The error message I get when I try to sort by guests is Exception in thread "main" java.lang.NullPointerException and then error code exit -1. The line that's causing the error is:
if (event[j].getGuests() > event[j + 1].getGuests()) {
You create an Array with the size 100.
After that, you fill it from index 0 to 7.
Every other place of the array remains null but the length is 100.
Then, you try to sort the array.
This throws a NullPointerException when you try to dereference (access) the 8. element:
event[j+1].getGuests()
I think you should use a smaller array(size 8) or a List.
How can i update the array of boolean (choosing) and int (number) when the variable N is update in the costructor of my class?
public class Lamport_Algorithm implements Runnable {
private static int N = 0;
private static boolean choosing[] = new boolean[N];
private static int number[] = new int[N];
private final int idProcess;
public Lamport_Algorithm(int idProcess) {
this.idProcess = idProcess;
if (N == 0) {
N = 1;
} else {
N += 1;
}
}
public void run() {
System.out.println("Hello" + "[" + idProcess + "]" + " There are: " + N + " Thread ");
for (int i = 0; i < N; i++) {
System.out.println(choosing[i]);
}
} }
This is the Main:
public class MainTest {
public static void main(String[] args){
Lamport_Algorithm a = new Lamport_Algorithm(1);
Thread T1 = new Thread (a);
T1.start();
}
}
You can initialize both arrays inside the constructor like below.
Your full version of code.
class Lamport_Algorithm implements Runnable {
private static int N = 0;
private static boolean choosing[];
private static int number[];
private final int idProcess;
public Lamport_Algorithm(int idProcess) {
this.idProcess = idProcess;
if (N == 0) {
N = 1;
} else {
N += 1;
}
choosing = new boolean[N];
number = new int[N];
}
public void run() {
System.out.println("Hello" + "[" + idProcess + "]" + " There are: " + N + " Thread ");
for (int i = 0; i < N; i++) {
System.out.println(choosing[i]);
}
}
}
class MainTest {
public static void main(String[] args){
Lamport_Algorithm a = new Lamport_Algorithm(1);
Thread T1 = new Thread (a);
T1.start();
}
}
I've used to site for many commands I had trouble using and it was very helpful. I thought you guys might be able to help me out and help me understand what i'm doing wrong here. The "Rabbit"/"R" is moving as I wanted, however the old position is not resetting its old value from the copied array. Logic for winning and losing aren't debugged, yet so ignore that.
EDIT*
I can't shorten the code due to the relations between the array has with the program. The precise description for the error is when the "Rabbit"/"R" moves from (Using representative values) GridCompOne[5][5] to GridCompOne[4][5] going "up" on the "grid" I have a second array called GridCompTwo which is a copied version of the first grid when the random values were generated. What is supposed to happen is the Rabbit's value, which = 4 is supposed to replace GridCompOne[4][5] to = 4 and the old position GridCompOne[5][5] is supposed to be replaced with GridCompTwo[5][5] old value being 3 which is supposed to represent the ground value I have assigned. But the replacing of the value doesn't seem to work.
import java.util.Random;
import java.util.Scanner;
public class SurvivalGameVersionTwo
{
private int Repeat;
public int WinLose = (1);
private int Turn = (1);
public static void main(String[] args)
{
String User;
int Repeat = (0);
//Creating Objects
SurvivalGameVersionTwo game = new SurvivalGameVersionTwo();
Score score = new Score();
Grid grid = new Grid();
Spawner spawner = new Spawner();
Display display = new Display();
User user = new User();
Time time = new Time();
Logic logic = new Logic();
Movement movement = new Movement();
//Calling object's class methods
Intro();
User = GetUser();
user.setName(User);
while (Repeat > 2);
{
game.Ready();
grid.RandomGridGenerator();
spawner.RabbitWolfSpawner();
movement.Copy();
while (game.WinLose <= 2)
{
display.UserGrid();
game.Turn = Turns(game.Turn);
movement.Movement();
game.WinLose = logic.WinLose(game.Turn);
time.Delay();
}
display.UserGrid();
Repeat = Repeat();
game.WinLose = (1);
}
}
public static void Intro()
{
System.out.printf("Welcome to the Rabbit Survival Game!\n");
System.out.println("Rules to win: Rabbit must cross the bridge.");
System.out.println("Rules to lose: Rabbir drowns in the water, \n"+
"eaten by the wolf, or starve to death in 30 turns.");
System.out.println("------------------------------------------");
}
public static String GetUser()
{
Scanner Input = new Scanner (System.in);
String Name;
System.out.println("Please type in your name please.");
Name = Input.next();
return Name;
}
public static void Ready()
{
Scanner Input = new Scanner (System.in);
String Ready;
String Yes = ("Yes");
String No = ("No");
System.out.println("Are you ready to play?");
System.out.println("Type in 'Yes', or 'No' to continue.");
Ready = Input.next();
if (Ready.equals(Yes) == true)
{
System.out.println("Lets begin!!!");
}
else if (Ready.equals(No) == true)
{
System.out.println("Goodbye, and hope you come back to play again.");
System.exit(0);
}
else
{
System.out.println("There was an error!!! Restart the program to try again.");
System.exit(0);
}
}
public static int Turns(int turns)
{
int Turns;
System.out.printf("Turn %d.",turns);
Turns = (turns + 1);
return Turns;
}
public static int Repeat()
{
Scanner Input = new Scanner (System.in);
int repeat;
System.out.println("Do you wish to play again?");
repeat = Input.nextInt();
return repeat;
}
}
class User
{
private String Name;
public void UserInfo(String name)
{
this.Name=name;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
class Score
{
public static int Total = 0;
public static int Win = 0;
public static int Lose = 0;
public static double Ratio = 0;
}
class Grid {
public static int[][] GridCompOne = new int[10][10];
public static int[] Rabbit = new int[2];
public static int[] Wolf = new int[2];
public static void RandomGridGenerator() {
Random r = new Random();
int i = 1;
int j = 1;
int k = 0;
int Low = 1;
int High = 3;
int Random;
//parameters for bridge and water spawning
while (k <= 9) {
Random = r.nextInt(High - Low) + Low;
GridCompOne[0][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][0] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[9][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][9] = Random;
k++;
}
while (i <= 8) {
while (j <= 8) {
GridCompOne[i][j] = 3;
j++;
}
j = 1;
i++;
}
}
}
class Spawner extends Grid
{
public static void RabbitWolfSpawner()
{
Random r = new Random();
int Low = 1;
int High = 8;
int XAxis;
int YAxis;
int Random;
//Rabbit
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 4;
Rabbit[0] = XAxis;
Rabbit[1] = YAxis;
//Wolf
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 5;
Wolf[0] = XAxis;
Wolf[1] = YAxis;
}
}
class Movement extends Grid
{
private static int[][] GridCompTwo = new int[10][10];
public static void Copy()
{
System.arraycopy(GridCompOne, 0, GridCompTwo, 0, GridCompOne.length);
}
//Rabbit and Wolf Movement
public static void Movement()
{
int High = 4;
int Low = 1;
Random R = new Random();
int Random = R.nextInt(High - Low) + Low;
//Rabbit
switch (Random)
{
case 1:
{
//Up
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] - 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] - 1);
break;
}
case 2:
{
//Down
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] + 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] + 1);
break;
}
case 3:
{
//Left
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] - 1] = 4;
Rabbit[1] = (Rabbit[1] - 1);
break;
}
case 4:
{
//Right
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] + 1] = 4;
Rabbit[1] = (Rabbit[1] + 1);
break;
}
default:
{
System.out.println("There was an error!!!");
System.exit(0);
}
}
Random = R.nextInt(High - Low) + Low;
//Wolf
switch (Random)
{
case 1: {
//Up
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] - 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] - 1);
break;
}
case 2: {
//Down
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] + 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] + 1);
break;
}
case 3: {
//Left
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] - 1] = 5;
Wolf[1] = (Wolf[1] - 1);
break;
}
case 4: {
//Right
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] + 1] = 5;
Wolf[1] = (Wolf[1] + 1);
break;
}
default: {
System.out.println("There was an error!!!");
System.exit(0);
}
}
}
}
class Display extends Movement
{
private static char[][] GridUser = new char[10][10];
public static void UserGrid()
{
int i = 0;
int j = 0;
char Letter = ' ';
System.out.println("---------------------");
while (i <= 9)
{
while (j <= 9)
{
System.out.print("|");
switch (GridCompOne[i][j])
{
case 1:
{
//Water
Letter = '~';
break;
}
case 2:
{
//Bridge
Letter = '=';
break;
}
case 3:
{
//Ground
Letter = ',';
break;
}
case 4:
{
//Rabbit
Letter = 'R';
break;
}
case 5:
{
//Wolf
Letter = 'W';
break;
}
default:
{
//Error!!!
System.out.println("There was an error in the program!!!");
System.exit(0);
}
}
GridUser[i][j] = Letter;
System.out.print(GridUser[i][j]);
j++;
}
System.out.print("|");
System.out.println();
System.out.println("---------------------");
j = 0;
i++;
}
}
}
class Logic extends Grid
{
public static int WinLose(int counter)
{
int winlose = (0);
if(GridCompOne[Rabbit[0]][Rabbit[1]]==1)
{
System.out.println("The Rabbit has drowned!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==2)
{
System.out.println("The Rabbit has Escaped!");
System.out.println("Game over!");
Score.Win = Score.Win + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==5)
{
System.out.println("The Rabbit has been Eaten by the Wolf!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(counter>30)
{
System.out.println("The Rabbit has starved to death");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else
{
System.out.println(" (Next Turn in a couple seconds)");
}
return winlose;
}
}
class Time
{
public static void Delay()
{
try
{
long Seconds = (2000);
Thread.sleep(Seconds);
}
catch (InterruptedException e)
{
System.out.println("...");
}
}
}
The root cause for the problem is System.arraycopy. As of my understanding it is copying reference instead of values (may be i am wrong).
i changed to manual copy then it is working fine up to the logic of replacing array. Please check below modified code with my comments
import java.util.Random;
import java.util.Scanner;
public class SurvivalGameVersionTwo
{
private int Repeat;
public int WinLose = (1);
private int Turn = (1);
public static void main(String[] args)
{
String User;
int Repeat = (3);//changed: to enter into while loop Repeat should be more than 2
//Creating Objects
SurvivalGameVersionTwo game = new SurvivalGameVersionTwo();
Score score = new Score();
Grid grid = new Grid();
Spawner spawner = new Spawner();
Display display = new Display();
User user = new User();
Time time = new Time();
Logic logic = new Logic();
Movement movement = new Movement();
//Calling object's class methods
Intro();
User = GetUser();
user.setName(User);
while (Repeat > 2)//changed: removed ;
{
game.Ready();
grid.RandomGridGenerator();
movement.Copy();//changed:First copy then change GridCompOne array
spawner.RabbitWolfSpawner();
while (game.WinLose <= 2)
{
display.UserGrid();
game.Turn = Turns(game.Turn);
movement.Movement();
game.WinLose = logic.WinLose(game.Turn);
time.Delay();
}
display.UserGrid();
Repeat = Repeat();
game.WinLose = (1);
}
}
public static void Intro()
{
System.out.printf("Welcome to the Rabbit Survival Game!\n");
System.out.println("Rules to win: Rabbit must cross the bridge.");
System.out.println("Rules to lose: Rabbir drowns in the water, \n"+
"eaten by the wolf, or starve to death in 30 turns.");
System.out.println("------------------------------------------");
}
public static String GetUser()
{
Scanner Input = new Scanner (System.in);
String Name;
System.out.println("Please type in your name please.");
Name = Input.next();
return Name;
}
public static void Ready()
{
Scanner Input = new Scanner (System.in);
String Ready;
String Yes = ("Yes");
String No = ("No");
System.out.println("Are you ready to play?");
System.out.println("Type in 'Yes', or 'No' to continue.");
Ready = Input.next();
if (Ready.equals(Yes) == true)
{
System.out.println("Lets begin!!!");
}
else if (Ready.equals(No) == true)
{
System.out.println("Goodbye, and hope you come back to play again.");
System.exit(0);
}
else
{
System.out.println("There was an error!!! Restart the program to try again.");
System.exit(0);
}
}
public static int Turns(int turns)
{
int Turns;
System.out.printf("Turn %d.",turns);
Turns = (turns + 1);
return Turns;
}
public static int Repeat()
{
Scanner Input = new Scanner (System.in);
int repeat;
System.out.println("Do you wish to play again?");
repeat = Input.nextInt();
return repeat;
}
}
class User
{
private String Name;
public void UserInfo(String name)
{
this.Name=name;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
class Score
{
public static int Total = 0;
public static int Win = 0;
public static int Lose = 0;
public static double Ratio = 0;
}
class Grid {
public static int[][] GridCompOne = new int[10][10];
public static int[] Rabbit = new int[2];
public static int[] Wolf = new int[2];
public static void RandomGridGenerator() {
Random r = new Random();
int i = 1;
int j = 1;
int k = 0;
int Low = 1;
int High = 3;
int Random;
//parameters for bridge and water spawning
while (k <= 9) {
Random = r.nextInt(High - Low) + Low;
GridCompOne[0][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][0] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[9][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][9] = Random;
k++;
}
while (i <= 8) {
while (j <= 8) {
GridCompOne[i][j] = 3;
j++;
}
j = 1;
i++;
}
}
}
class Spawner extends Grid
{
public static void RabbitWolfSpawner()
{
Random r = new Random();
int Low = 1;
int High = 8;
int XAxis;
int YAxis;
int Random;
//Rabbit
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 4;
Rabbit[0] = XAxis;
Rabbit[1] = YAxis;
//Wolf
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 5;
Wolf[0] = XAxis;
Wolf[1] = YAxis;
}
}
class Movement extends Grid
{
private static int[][] GridCompTwo = new int[10][10];
public static void Copy()
{
//System.arraycopy(GridCompOne, 0, GridCompTwo, 0, GridCompOne.length);
//changed
//As of my understanding System.arraycopy is not coping values , it is copying references
for(int i=0;i<GridCompOne.length;i++){
for(int j=0;j<GridCompOne[i].length;j++){
GridCompTwo[i][j]=GridCompOne[i][j];
}
}
}
//Rabbit and Wolf Movement
public static void Movement()
{
int High = 4;
int Low = 1;
Random R = new Random();
int Random = R.nextInt(High - Low) + Low;
//Rabbit
switch (Random)
{
case 1:
{
//Up
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] - 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] - 1);
break;
}
case 2:
{
//Down
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] + 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] + 1);
break;
}
case 3:
{
//Left
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] - 1] = 4;
Rabbit[1] = (Rabbit[1] - 1);
break;
}
case 4:
{
//Right
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] + 1] = 4;
Rabbit[1] = (Rabbit[1] + 1);
break;
}
default:
{
System.out.println("There was an error!!!");
System.exit(0);
}
}
Random = R.nextInt(High - Low) + Low;
//Wolf
switch (Random)
{
case 1: {
//Up
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] - 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] - 1);
break;
}
case 2: {
//Down
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] + 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] + 1);
break;
}
case 3: {
//Left
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] - 1] = 5;
Wolf[1] = (Wolf[1] - 1);
break;
}
case 4: {
//Right
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] + 1] = 5;
Wolf[1] = (Wolf[1] + 1);
break;
}
default: {
System.out.println("There was an error!!!");
System.exit(0);
}
}
}
}
class Display extends Movement
{
private static char[][] GridUser = new char[10][10];
public static void UserGrid()
{
int i = 0;
int j = 0;
char Letter = ' ';
System.out.println("---------------------");
while (i <= 9)
{
while (j <= 9)
{
System.out.print("|");
switch (GridCompOne[i][j])
{
case 1:
{
//Water
Letter = '~';
break;
}
case 2:
{
//Bridge
Letter = '=';
break;
}
case 3:
{
//Ground
Letter = ',';
break;
}
case 4:
{
//Rabbit
Letter = 'R';
break;
}
case 5:
{
//Wolf
Letter = 'W';
break;
}
default:
{
//Error!!!
System.out.println("There was an error in the program!!!");
System.exit(0);
}
}
GridUser[i][j] = Letter;
System.out.print(GridUser[i][j]);
j++;
}
System.out.print("|");
System.out.println();
System.out.println("---------------------");
j = 0;
i++;
}
}
}
class Logic extends Grid
{
public static int WinLose(int counter)
{
int winlose = (0);
if(GridCompOne[Rabbit[0]][Rabbit[1]]==1)
{
System.out.println("The Rabbit has drowned!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==2)
{
System.out.println("The Rabbit has Escaped!");
System.out.println("Game over!");
Score.Win = Score.Win + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==5)
{
System.out.println("The Rabbit has been Eaten by the Wolf!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(counter>30)
{
System.out.println("The Rabbit has starved to death");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else
{
System.out.println(" (Next Turn in a couple seconds)");
}
return winlose;
}
}
class Time
{
public static void Delay()
{
try
{
long Seconds = (2000);
Thread.sleep(Seconds);
}
catch (InterruptedException e)
{
System.out.println("...");
}
}
}
Thanks
The point of the program is to display a poker and bridge hand. Those far when I run the program I can get it to display the poker description and then if exits. I would like it to continue and display the a poker hand then the bridge description and a bridge hand. I feel like my issues are coming from the abstract DeckOfCards class but Im really not sure.
I put all the classes in the same file to make it easier to follow and edit while programming.
When the program fails it gives these errors
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52
at DeckOfCards.creatCardDeck(PlayCardGames.java:106)
at DeckOfCards.DeckOfCards(PlayCardGames.java:95)
at PlayCardGames.main(PlayCardGames.java:14)
Here is the program code it self (Thank you for editing it to format better)
import javax.swing.*;
import java.util.Random;
public class PlayCardGames {
public static void main(String[] args) {
Poker playPoker = new Poker();
playPoker.DeckOfCards();
playPoker.displayDescription();
playPoker.deal();
Bridge playBridge = new Bridge();
playBridge.DeckOfCards();
playBridge.displayDescription();
playBridge.deal();
}
}
//--------------------------------------------------------------------------------\\
interface DeckConstants{
final static int CARDS_IN_SUIT = 13;
final static int SUITS_IN_DECK = 4;
final static int CARDS_IN_DECK = CARDS_IN_SUIT * SUITS_IN_DECK;
}
//================================================================================\\
class Card{
private String suit;
private String rank;
private int rankIndex;
public Card(int suitIndex, int rankIndex){
setSuit(suitIndex);
setRank(rankIndex);
}
public String getSuit() {
if (suit.equalsIgnoreCase("Hearts")){ suit = "\u2665";}
else if (suit.equalsIgnoreCase("Diamonds")) { suit = "\u2666"; }
else if (suit.equalsIgnoreCase("Clubs")) { suit = "\u2663"; }
else if(suit.equalsIgnoreCase("Spades")) { suit = "\u2660"; }
return suit;
}
public void setSuit(int suitIndex) {
if (suitIndex == 1) {suit = "Spades";}
else if (suitIndex == 2) {suit = "Hearts";}
else if (suitIndex == 3) {suit = "Diamonds";}
else if(suitIndex == 4) {suit = "Clubs";}
}
public String getRank() {
if (rankIndex == 1) {rank = "Ace";}
else if (rankIndex == 11) {rank = "Jack";}
else if (rankIndex == 12) {rank = "Queen";}
else if(rankIndex == 13) {rank = "King";}
return rank;
}
public void setRank(int rankIndex) {
if (this.rankIndex >= 13){
this.rankIndex = 13;}
else if(this.rankIndex <= 1) {
this.rankIndex = 1;}
}
public String toString(String rank, String suit) {
return getRank() +" of " + getSuit();
}
}
//=================================================================================\\
abstract class DeckOfCards implements DeckConstants{
protected Card[] deck = new Card[CARDS_IN_DECK];
public void DeckOfCards(){
creatCardDeck();
shuffle(deck);
}
public void creatCardDeck() {
int numberOfCards = 0;
for (int suitCounter = 1; suitCounter < CARDS_IN_SUIT; suitCounter++)
{
for (int rankCounter = 1; rankCounter < CARDS_IN_SUIT; rankCounter++)
{
deck[numberOfCards] = new Card(suitCounter, rankCounter);
numberOfCards++;
}
}
}
public void shuffle(Card[] temp){
Random rnd = new Random();
for (int k = temp.length; k > 1; k--){
int i = k - 1;
int j = rnd.nextInt(k);
Card tmp = temp[i];
temp[i] = temp[j];
temp[j]= tmp;
}
}
public abstract void displayDescription();
public abstract void deal();
}
//===============================================================================\\
class Poker extends DeckOfCards{
private int cardsDealt = 5;
private int index = 0;
public void Poker(){
displayDescription();
deal();
}
public void displayDescription(){
String desc = "In poker, players bet on hands" +
"\n Winner can bluff or must have the highest hand if called";
JOptionPane.showMessageDialog(null, desc);
}
public void deal() {
String message = "Your Poker hand:\n";
for (int x = index; x < cardsDealt; x++){
message += deck[index] + "\n";
index++;
}
if (index == CARDS_IN_DECK){
shuffle(deck);
index = 0;
}
JOptionPane.showMessageDialog(null, message);
}
}
//===============================================================================\\
class Bridge extends DeckOfCards{
private int cardsDealt = 13;
private int index = 0;
public void Bridge(){
displayDescription();
deal();
}
public void displayDescription(){
String desc = "In bride, partners bid on how many tricks they will take." +
"\n The high bid determines a trump suit";
JOptionPane.showMessageDialog(null, desc);
}
public void deal() {
String message = "Your Bridge hand:\n";
for (int x = index; x < cardsDealt; x++){
message += deck[index] + "\n";
index++;
}
if (index == CARDS_IN_DECK){
shuffle(deck);
index = 0;
}
JOptionPane.showMessageDialog(null, message);
}
}
You know what, I think it is really simple:
Here is your code:
for (int suitCounter = 1; suitCounter < CARDS_IN_SUIT; suitCounter++)
{
for (int rankCounter = 1; rankCounter < CARDS_IN_SUIT; rankCounter++)
{
I think just maybe it should be:
for (int suitCounter = 1; suitCounter < SUITS_IN_DECK; suitCounter++)
{
for (int rankCounter = 1; rankCounter < CARDS_IN_SUIT; rankCounter++)
{