And below is a code an attempted code but I keep getting these errors: Could any
ID: 3730983 • Letter: A
Question
And below is a code an attempted code but I keep getting these errors:
Could anyone able be to point out the errors made and fix the code? (See below)
Card.java:
public class Card{
//Initialize instance variables:
private String suit;
private String rank;
private int value;
//Initialize constructor
public Card(){
}
//Another constructor that creates a 'Card' object with the attributes based on user input:
public Card(String suit, String rank){
this.suit = suit;
this.rank = rank;
//The following if-statements below will determine the value of the card based on the card's rank:
if(rank.equals("2")){
value = 2;
}
else if(rank.equals("3")){
value = 3;
}
else if(rank.equals("4")){
value = 4;
}
else if(rank.equals("5")){
value = 5;
}
else if(rank.equals("6")){
value = 6;
}
else if(rank.equals("7")){
value = 7;
}
else if(rank.equals("8")){
value = 8;
}
else if(rank.equals("9")){
value = 9;
}
else if(rank.equals("10")){
value = 10;
}
else if(rank.equals("Jack")){
value = 11;
}
else if(rank.equals("Queen")){
value = 12;
}
else if(rank.equals("King")){
value = 13;
}
else if(rank.equals("Ace")){
value = 14;
}
//^
}
//Initialize getter methods:
public String getSuit(){
return suit;
}
public String getRank(){
return rank;
}
public int getValue(){
return value;
}
//^
//Initialize setter methods:
public void setSuit(String suit){
this.suit = suit;
}
public void setRank(String rank){
this.rank = rank;
}
public void setValue(int value){
this.value = value;
}
//^
public String toString(){ //toString is a method used to print out a Card object's attributes
return rank + " " + suit;
}
public Card copy(Card card){ //copy is a method which copies the attributes of a Card object to another created Card object
Card temp = new Card (card.getSuit(), card.getRank());
return temp;
}
public int isGreater(Card card){ //isGreater is a method which compares the value of 2 different Card objects.
int temp;
if (value > card.getValue()){ //If the current Card's value is greater than the Card being compared then temp is set to 1
temp = 1;
}
else if (value < card.getValue()){ //Else, if the Card that is being compared has a greater value than the current Card then temp is set to 2
temp = 2;
}
else { //Else, both Cards have the same value
temp = 3;
}
return temp; //Returns the value of temp after using the method isGreater
}
}
Deck.java:
import java.util.ArrayList; //Imports Array Lists
import java.util.Random; //Imports the Randomizer
public class Deck{
Random random = new Random();
//Initialize instance variables:
private ArrayList Deck = new ArrayList (52);
private ArrayList Shuffled = new ArrayList (52);
//Initialize constructor:
public Deck(){
//Initialize the string to blank values to avoid initialization error messages:
String suit = "";
String rank = "";
//The lines below are a combination of if-else statements and nested for-loops which completes a Deck by assigning their corresponding suites and ranks
for(int x = 0; x < 4; x++){
if(x == 0){
suit = "Clubs";
}
else if(x == 1){
suit = "Hearts";
}
else if(x == 2){
suit = "Spades";
}
else if(x == 3){
suit = "Diamonds";
}
for(int y = 1; y <= 13; y++){
if(y == 1){
rank = "Ace";
}
else if(y > 1 && y < 11){
rank = "" + y;
}
else if(y == 11){
rank = "Jack";
}
else if(y == 12){
rank = "Queen";
}
else if(y == 13){
rank = "King";
Card card = new Card(suit, rank);
Deck.add(card);
}
}
//^
}
}
public Card getFromShuffledDeck(int x){ //getFromShuffled is a method used when the user draws a Card from the shuffled deck
return Shuffled.get(x);
}
public void shuffle(){ //shuffle is a method that takes all Card objects from the Normal deck and shuffles the card in a random order
ArrayList usednums = new ArrayList (52); //usednums is an integer Array List that collects the used indexes
//For loop ensures that numsUsed contains 52 random numbers that do not repeat
for(int x = 0; x < 52; x++){ //Below is for-loop and while-loop combination which traversers through all Card objects in the Deck and keeps adding Card objects to the Shuffled deck in a random order
int cardnum = random.nextInt((51 - 0) + 1) + 0;
while(usednums.indexOf(cardnum) != -1){ //^
cardnum = random.nextInt((52 - 0) + 1) + 0;
usednums.add(x, cardnum); //Gets added to the usednums Array List
Shuffled.add(x, Deck.get(cardnum)); //Gets added to the Shuffled deck Array List
}
}
}
}
WarDemo.java:
import java.util.Scanner;
import java.util.ArrayList;
public class WarDemo{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String player1;
String player2;
String roundwinner = "";
String gamewinner = "";
boolean winner = false;
int temp;
int play = 1;
while(play != 0){//main outer loop
//creates a deck object and shuffles it
Deck deck = new Deck();
deck.shuffle();
//creates three Array Lists
ArrayList Deck1 = new ArrayList (56);
ArrayList Deck2 = new ArrayList (56);
ArrayList warDeck = new ArrayList (9);
//for loop adds 26 cards to Deck1 and Deck2
for(int x = 0; x < 26; x++){
Deck1.add(deck.getFromShuffledDeck(x));
Deck2.add(deck.getFromShuffledDeck(x + 26));
}
//Welcomes users, prompts for names
System.out.println("Welcome to WAR! Let's Play! ");
System.out.print("Enter the first player's name: ");
player1 = scan.nextLine();
System.out.print("Enter the second player's name: ");
player2 = scan.nextLine();
//displays header
System.out.println(player1 + " #Cards " + player2 + " #Cards Winner");
while(!winner){
//displays first card of Deck1 and Deck2, and how many cards are left in each
System.out.print(Deck1.get(0) + " " + Deck1.size() + " " + Deck2.get(0) + " " + Deck2.size() + " ");
int x = Deck1.get(0).isGreater(Deck2.get(0));
/*If one of the cards has a greater value than the other, program will add the first
card of BOTH decks to the end, and then remove the first card of BOTH decks */
if(x == 1){//Deck1 first card is greater than Deck2 first card
Deck1.add(Deck2.get(0));//
Deck1.add(Deck1.get(0));
Deck1.remove(0);
Deck2.remove(0);
roundwinner = player1;
}
if(x == 2){//Deck2 first card is greater than Deck1 first card
Deck2.add(Deck1.get(0));
Deck2.add(Deck2.get(0));
Deck2.remove(Deck2.get(0));
Deck1.remove(0);
roundwinner = player2;
}
if(x == 3)//alerts users that there is no winner this round, just a war
roundwinner = "WAR!";
System.out.println(roundwinner);
if(x == 3){//WAR!
war();
System.out.print(Deck1.get(0) + " " + Deck1.size() + " " + Deck2.get(0) + " " + Deck2.size() + " ");
/*If either player has 4 cards or less, then they do not have enough cards to go to
war, and the winner will automatically be the other person. This is tested until line
89 */
if(Deck1.size() <= 4){
roundwinner = player2;
System.out.println(roundwinner);
System.out.println(" " + player1 + " does not have enough cards to go to war.");
endwar();
gamewinner = player2;
break;
}
else if(Deck2.size() <= 4){
roundwinner = player1;
System.out.println(roundwinner);
System.out.println(" " + player2 + " does not have enough cards to go to war.");
System.out.println("***************************************END WAR****************************************");
gamewinner = player1;
break;
}
//Adds 4 cards to the warDeck from each player until line 98
for(int y = 0; y < 4 && Deck1.size() < 48; y++){
warDeck.add(Deck1.get(0));
Deck1.remove(0);
}
for(int y = 0; y < 4 && Deck2.size() < 48; y++){
warDeck.add(Deck2.get(0));
Deck2.remove(0);
}
//evalutes to see who the war winner is, whoever wins will gain all cards from
//war deck
temp = warDeck.get(3).isGreater(warDeck.get(7));
if(temp == 1){
while(warDeck.size() != 0){
Deck1.add(warDeck.get(0));
warDeck.remove(0);
roundwinner = player1;
}
}
else if(temp == 2){
while(warDeck.size() != 0){
Deck2.add(warDeck.get(0));
warDeck.remove(0);
roundwinner = player2;
}
}
else{//if there is another war, then program will then test to see if there
//is a winner by shifting all of the cards to the right
/*
warDeck.add(warDeck.get(3));
warDeck.remove(3);
warDeck.add(2, warDeck.get(7));
warDeck.remove(7);
*/
shift(warDeck);
temp = warDeck.get(3).isGreater(warDeck.get(7));
if(temp == 1){//if player 1 wins, then all cards from warDeck are added to Deck1
while(warDeck.size() != 0){
Deck1.add(warDeck.get(0));
warDeck.remove(0);
roundwinner = player1;
}
}
else if(temp == 2){//if player 2 wins, then all cards from warDeck are added to Deck2
while(warDeck.size() != 0){
Deck2.add(warDeck.get(0));
warDeck.remove(0);
roundwinner = player2;
}
}
}
System.out.println(roundwinner); //prints winner of war
endwar();
}
//if at any time one of the players has 52 cards, there will be a winner and
//inner loop will stop
if(Deck1.size() == 52){
gamewinner = player1;
winner = true;
}
if(Deck2.size() == 52){
gamewinner = player2;
winner = true;
}
}//end of inner loop
//congratulats winner, asks if they want to play again
System.out.println(gamewinner + " WINS! Congratulations!");
System.out.print("Play again (y/n)? ");
String option;
option = scan.nextLine().toLowerCase();
option = "" + option.charAt(0);
//while loop exists to error check
while(!(option.equals("y") || option.equals("n"))){
System.out.print("Invalid option. Please enter Y or N: ");
option = scan.nextLine().toUpperCase();
option = "" + option.charAt(0);
}
if(option.equals("y")){
play = 1;
}
else{
play = 0;
}
}//end of outer loop
System.out.print("Thank you for playing!");
}//end main method
public static void war(){
System.out.println("************************************************WAR*******************************************");
}
public static void endwar(){
System.out.println("************************************************END WAR***************************************");
}
public static void shift(ArrayList warDeck){
warDeck.add(warDeck.get(3));
warDeck.remove(3);
warDeck.add(2, warDeck.get(7));
warDeck.remove(7);
}
}//end class
Explanation / Answer
Hi, you have written amazing code. There are minor errors due to which your code is not running.
First of all, List Shuffled is not getting populated that is why you are getting ArrayIndexOutOfBoundsException. Also there are other errors :
(i) In Deck constructor, these lines should be outside else if(y==13). This was adding only Kings of all suits to the deck.
Card card = new Card(suit, rank);
Deck.add(card);
(ii) In shuffle(), first of all, the for loop you were using with counter x to add the card to shuffled deck at x was a bit wrong. Since the element only gets added if it is not already used but x keeps incrementing everytime which was giving you ArrayIndexOutOfBoundsException. I have changed the shuffle() method like this:
public void shuffle() { // shuffle is a method that takes all Card objects
// from the Normal deck and shuffles the card in a
// random order
ArrayList<Integer> usednums = new ArrayList<>(52); // usednums is an integer Array
// List that collects the used
// indexes
// For loop ensures that numsUsed contains 52 random numbers that do not
// repeat
System.out.println("Deck Size: "+Deck.size());
int x=0;
while(x<52) { // Below is for-loop and while-loop
// combination which traverses through
// all Card objects in the Deck and
// keeps adding Card objects to the
// Shuffled deck in a random order
int cardnum = random.nextInt((51 - 0) + 1) + 0;
//System.out.println("Card Number: "+cardnum);
while (usednums.indexOf(cardnum) == -1) { // ^
usednums.add(x,cardnum); // Gets added to the usednums Array
//System.out.println("Geting card from Deck: "+Deck.get(cardnum)); // List
Shuffled.add(x,Deck.get(cardnum)); // Gets added to the
System.out.println("Shuffled Deck Cards Size: "+Shuffled.size()+" "+Deck.get(cardnum).getRank()+" "+Deck.get(cardnum).getSuit()); // Shuffled deck Array List
x++;
}
}
}
This solves all your errors and your code is executed successfully.
(iii) One more thing I noticed is whenever the user plays again, the game is not played and winner remains the same. This is because the winner is not reset at the start of another round. So winner needs to be declared inside the outer loop.
For your reference, I'll just paste the entire code below. you can execute and see the result.
Card.java
package com.game.war;
public class Card {
// Initialize instance variables:
private String suit;
private String rank;
private int value;
// Initialize constructor
public Card() {
}
// Another constructor that creates a 'Card' object with the attributes
// based on user input:
public Card(String suit, String rank) {
this.suit = suit;
this.rank = rank;
// The following if-statements below will determine the value of the
// card based on the card's rank:
if (rank.equals("2")) {
value = 2;
} else if (rank.equals("3")) {
value = 3;
} else if (rank.equals("4")) {
value = 4;
} else if (rank.equals("5")) {
value = 5;
} else if (rank.equals("6")) {
value = 6;
} else if (rank.equals("7")) {
value = 7;
} else if (rank.equals("8")) {
value = 8;
} else if (rank.equals("9")) {
value = 9;
} else if (rank.equals("10")) {
value = 10;
} else if (rank.equals("Jack")) {
value = 11;
} else if (rank.equals("Queen")) {
value = 12;
} else if (rank.equals("King")) {
value = 13;
} else if (rank.equals("Ace")) {
value = 14;
}
// ^
}
// Initialize getter methods:
public String getSuit() {
return suit;
}
public String getRank() {
return rank;
}
public int getValue() {
return value;
}
// ^
// Initialize setter methods:
public void setSuit(String suit) {
this.suit = suit;
}
public void setRank(String rank) {
this.rank = rank;
}
public void setValue(int value) {
this.value = value;
}
// ^
public String toString() { // toString is a method used to print out a Card
// object's attributes
return rank + " " + suit;
}
public Card copy(Card card) { // copy is a method which copies the
// attributes of a Card object to another
// created Card object
Card temp = new Card(card.getSuit(), card.getRank());
return temp;
}
public int isGreater(Card card) { // isGreater is a method which compares
// the value of 2 different Card
// objects.
int temp;
if (value > card.getValue()) { // If the current Card's value is greater
// than the Card being compared then
// temp is set to 1
temp = 1;
} else if (value < card.getValue()) { // Else, if the Card that is being
// compared has a greater value
// than the current Card then
// temp is set to 2
temp = 2;
} else { // Else, both Cards have the same value
temp = 3;
}
return temp; // Returns the value of temp after using the method
// isGreater
}
}
Deck.java:
package com.game.war;
import java.util.ArrayList; //Imports Array Lists
import java.util.List;
import java.util.Random; //Imports the Randomizer
public class Deck {
Random random = new Random();
// Initialize instance variables:
private ArrayList<Card> Deck = new ArrayList<>(52);
private ArrayList<Card> Shuffled = new ArrayList<>(52);
// Initialize constructor:
public Deck() {
// Initialize the string to blank values to avoid initialization error
// messages:
String suit = "";
String rank = "";
// The lines below are a combination of if-else statements and nested
// for-loops which completes a Deck by assigning their corresponding
// suites and ranks
for (int x = 0; x < 4; x++) {
if (x == 0) {
suit = "Clubs";
} else if (x == 1) {
suit = "Hearts";
} else if (x == 2) {
suit = "Spades";
} else if (x == 3) {
suit = "Diamonds";
}
for (int y = 1; y <= 13; y++) {
if (y == 1) {
rank = "Ace";
} else if (y > 1 && y < 11) {
rank = "" + y;
} else if (y == 11) {
rank = "Jack";
} else if (y == 12) {
rank = "Queen";
} else if (y == 13) {
rank = "King";
}
Card card = new Card(suit, rank);
Deck.add(card);
//System.out.println("Deck card: "+card.getRank()+" "+card.getSuit());
}
// ^
}
}
public Card getFromShuffledDeck(int x) { // getFromShuffled is a method used
// when the user draws a Card
if(!Shuffled.isEmpty()) // from the shuffled deck
return Shuffled.get(x);
return null;
}
public void shuffle() { // shuffle is a method that takes all Card objects
// from the Normal deck and shuffles the card in a
// random order
ArrayList<Integer> usednums = new ArrayList<>(52); // usednums is an integer Array
// List that collects the used
// indexes
// For loop ensures that numsUsed contains 52 random numbers that do not
// repeat
System.out.println("Deck Size: "+Deck.size());
int x=0;
while(x<52) { // Below is for-loop and while-loop
// combination which traverses through
// all Card objects in the Deck and
// keeps adding Card objects to the
// Shuffled deck in a random order
int cardnum = random.nextInt((51 - 0) + 1) + 0;
//System.out.println("Card Number: "+cardnum);
while (usednums.indexOf(cardnum) == -1) { // ^
usednums.add(x,cardnum); // Gets added to the usednums Array
//System.out.println("Geting card from Deck: "+Deck.get(cardnum)); // List
Shuffled.add(x,Deck.get(cardnum)); // Gets added to the
System.out.println("Shuffled Deck Cards Size: "+Shuffled.size()+" "+Deck.get(cardnum).getRank()+" "+Deck.get(cardnum).getSuit()); // Shuffled deck Array List
x++;
}
}
}
}
WarDemo.java
package com.game.war;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class WarDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String player1;
String player2;
String roundwinner = "";
String gamewinner = "";
int temp;
int play = 1;
while (play != 0) {// main outer loop
boolean winner = false; // set winner to false everytime the game starts
// creates a deck object and shuffles it
Deck deck = new Deck();
deck.shuffle();
// creates three Array Lists
ArrayList<Card> Deck1 = new ArrayList<>(56);
ArrayList<Card> Deck2 = new ArrayList<>(56);
ArrayList<Card> warDeck = new ArrayList<>(9);
// for loop adds 26 cards to Deck1 and Deck2
for (int x = 0; x < 26; x++) {
System.out.println("Getting from shuffled deck: Position: "+x+", "+(x+26));
Deck1.add(deck.getFromShuffledDeck(x));
Deck2.add(deck.getFromShuffledDeck(x+26));
}
// Welcomes users, prompts for names
System.out.println("Welcome to WAR! Let's Play! ");
System.out.print("Enter the first player's name: ");
player1 = scan.nextLine();
System.out.print("Enter the second player's name: ");
player2 = scan.nextLine();
// displays header
System.out.println(player1 + " #Cards " + player2 + " #Cards Winner");
while (!winner) {
// displays first card of Deck1 and Deck2, and how many cards
// are left in each
System.out.print(
Deck1.get(0) + " " + Deck1.size() + " " + Deck2.get(0) + " " + Deck2.size() + " ");
int x = Deck1.get(0).isGreater(Deck2.get(0));
/*
* If one of the cards has a greater value than the other,
* program will add the first card of BOTH decks to the end, and
* then remove the first card of BOTH decks
*/
if (x == 1) {// Deck1 first card is greater than Deck2 first
// card
Deck1.add(Deck2.get(0));//
Deck1.add(Deck1.get(0));
Deck1.remove(0);
Deck2.remove(0);
roundwinner = player1;
}
if (x == 2) {// Deck2 first card is greater than Deck1 first
// card
Deck2.add(Deck1.get(0));
Deck2.add(Deck2.get(0));
Deck2.remove(Deck2.get(0));
Deck1.remove(0);
roundwinner = player2;
}
if (x == 3)// alerts users that there is no winner this round,
// just a war
roundwinner = "WAR!";
System.out.println(roundwinner);
if (x == 3) {// WAR!
war();
System.out.print(Deck1.get(0) + " " + Deck1.size() + " " + Deck2.get(0) + " " + Deck2.size()
+ " ");
/*
* If either player has 4 cards or less, then they do not
* have enough cards to go to war, and the winner will
* automatically be the other person. This is tested until
* line 89
*/
if (Deck1.size() <= 4) {
roundwinner = player2;
System.out.println(roundwinner);
System.out.println(" " + player1 + " does not have enough cards to go to war.");
endwar();
gamewinner = player2;
break;
} else if (Deck2.size() <= 4) {
roundwinner = player1;
System.out.println(roundwinner);
System.out.println(" " + player2 + " does not have enough cards to go to war.");
System.out.println(
"***************************************END WAR****************************************");
gamewinner = player1;
break;
}
// Adds 4 cards to the warDeck from each player until line
// 98
for (int y = 0; y < 4 && Deck1.size() < 48; y++) {
warDeck.add(Deck1.get(0));
Deck1.remove(0);
}
for (int y = 0; y < 4 && Deck2.size() < 48; y++) {
warDeck.add(Deck2.get(0));
Deck2.remove(0);
}
// evalutes to see who the war winner is, whoever wins will
// gain all cards from
// war deck
temp = warDeck.get(3).isGreater(warDeck.get(7));
if (temp == 1) {
while (warDeck.size() != 0) {
Deck1.add(warDeck.get(0));
warDeck.remove(0);
roundwinner = player1;
}
} else if (temp == 2) {
while (warDeck.size() != 0) {
Deck2.add(warDeck.get(0));
warDeck.remove(0);
roundwinner = player2;
}
} else {// if there is another war, then program will then
// test to see if there
// is a winner by shifting all of the cards to the right
/*
* warDeck.add(warDeck.get(3)); warDeck.remove(3);
* warDeck.add(2, warDeck.get(7)); warDeck.remove(7);
*/
shift(warDeck);
temp = warDeck.get(3).isGreater(warDeck.get(7));
if (temp == 1) {// if player 1 wins, then all cards from
// warDeck are added to Deck1
while (warDeck.size() != 0) {
Deck1.add(warDeck.get(0));
warDeck.remove(0);
roundwinner = player1;
}
} else if (temp == 2) {// if player 2 wins, then all
// cards from warDeck are added
// to Deck2
while (warDeck.size() != 0) {
Deck2.add(warDeck.get(0));
warDeck.remove(0);
roundwinner = player2;
}
}
}
System.out.println(roundwinner); // prints winner of war
endwar();
}
// if at any time one of the players has 52 cards, there will be
// a winner and
// inner loop will stop
if (Deck1.size() == 52) {
gamewinner = player1;
winner = true;
}
if (Deck2.size() == 52) {
gamewinner = player2;
winner = true;
}
} // end of inner loop
// congratulats winner, asks if they want to play again
System.out.println(gamewinner + " WINS! Congratulations!");
System.out.print("Play again (y/n)? ");
String option;
option = scan.nextLine().toLowerCase();
option = "" + option.charAt(0);
// while loop exists to error check
while (!(option.equals("y") || option.equals("n"))) {
System.out.print("Invalid option. Please enter Y or N: ");
option = scan.nextLine().toUpperCase();
option = "" + option.charAt(0);
}
if (option.equals("y")) {
play = 1;
} else {
play = 0;
}
} // end of outer loop
System.out.print("Thank you for playing!");
}// end main method
public static void war() {
System.out.println(
"************************************************WAR*******************************************");
}
public static void endwar() {
System.out.println(
"************************************************END WAR***************************************");
}
public static void shift(List<Card> warDeck) {
warDeck.add(warDeck.get(3));
warDeck.remove(3);
warDeck.add(2, warDeck.get(7));
warDeck.remove(7);
}
}// end class
That's all. Please contact in case of any issue(s) :)
And don't forget to rate if your query is solved ;)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.