Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement layout not right

I am trying to create a program to assign cards a value and then depending which player gets the highest card then they win a point now the area which i cant get to work is the last if statement as it does it after every round not the 7 as needed.


import java.util.*;

public class Card {

    public static void main(String[] args) {

        int player1= 0;
        int player2 = 0;
        int i = 1;

        while ( i <= 7) {
            int player1Card = (int) (Math.random() * 13) + 1;
            int player2Card = (int) (Math.random() * 13) + 1;

            System.out.println("player 1 = " + player1Card);
            System.out.println("player 2 = " + player2Card);

           if (player1Card > player2Card) {
                System.out.println("Player 1 wins!!!");
                player1 = player1 + 1;
            } else if (player1Card == player2Card){
                System.out.println("It's a bore draw");
                player1 = player1 + 0;
                player2= player2 + 0;
            } else {
                System.out.println("Player 2 wins!!!!!");
                player2 = player2 + 1;
            }
            System.out.println("Player 1 points " + player1);
            System.out.println("Player 2 points " + player2);
            i++;

            if (player1 > player2) {
                System.out.println("The winner is player 1 with " + player1 + " points");
            } else if (player1 == player2) {
                System.out.println("Its a draw");
            } else {
                System.out.println("The winner is Player 2 with " + player2 + " points");
            }     
      }
like image 702
Jonny_Appleby12 Avatar asked Mar 28 '26 18:03

Jonny_Appleby12


1 Answers

Your if statement needs to come after the end of the while loop. Move the last } to be before the if statement you want to be executed after all 7 times have run.

like image 69
Ina Avatar answered Mar 30 '26 09:03

Ina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!