Issue
public class War2
{
public void warCall()
{
System.out.println("WAR is CALLED!");
for(int counter = 1; counter <= 11; ++counter)
{
Dealer gameDealer = new Dealer();
Card computerCard = new Card();
Card playerCard = new Card();
String computerCardSuit = computerCard.getSuit((int)(Math.random() * 100) % 4 + 1);
int computerCardRank = computerCard.getRank();
String playerCardSuit = playerCard.getSuit((int)(Math.random() * 100) % 4 + 1);
int playerCardRank = playerCard.getRank();
boolean playerWins = (playerCardRank > computerCardRank);
boolean computerWins = (computerCardRank > playerCardRank);
boolean tie = (computerCardRank == playerCardRank);
String result = "";
if(counter < 11)
result = "Discard";
if(counter == 11 && (computerWins))
result = "Computer wins";
else
if(counter == 11 && (playerWins))
result = "Player wins";
else
if(counter == 11 && (tie))
result = "Tie";
System.out.println(computerCardRank + " of " + computerCardSuit + "\t\t" +
playerCardRank + " of " + playerCardSuit + "\t\t" + result);
}
}
}
This class(War2) and its method( warCall() ) are called from another class when there is a tie in a game of War. This is the way the output looks:
This is the way the game starts. This part of the program works fine.A Dealer class executes the code below. When the result is a tie (card ranks are equal, in this case 4), the Dealer class invokes the warCall() method from the War2 class. The car suit is assigned randomly using a switch statement from a randomly drawn number from 1 to 4. The getSuit() method takes an integer argument but returns a String, depending on the random number drawn. This information doesn't relate exactly to my question, but I want to give an idea of how the program works.
--------------------------------------------------------
Computer Player Human Player Result
4 of Clubs 4 of Hearts Tie
-------------------------------------------------------
This is the output from the War2 class:
WAR is CALLED!
2 of Hearts 12 of Clubs Discard
10 of Spades 3 of Spades Discard
8 of Spades 1 of Clubs Discard
4 of Spades 13 of Hearts Discard
1 of Diamonds 6 of Spades Discard
3 of Diamonds 3 of Diamonds Discard
11 of Diamonds 10 of Hearts Discard
8 of Hearts 9 of Clubs Discard
13 of Hearts 9 of Diamonds Discard
1 of Diamonds 1 of Clubs Discard
3 of Spades 5 of Spades Player wins
What I need is for the above process to repeat in the event of a tie (when counter is 11 and rank of both cards is the same), within the War2 class. I have attached my code for War2 so that you can see what I have done so far. How can I make all of this output repeat if there is a tie until there is a clear winner?
I have tried using do and do while loops without success.
Solution
Simply loop if the result is "Tie"
String result = "";
while(result.equals("") || result.equals("Tie")){
// do the for loop
}
Answered By - fauzimh
Answer Checked By - Katrina (JavaFixing Volunteer)