Java with If statement and random numbers

Jamal :

i'm a beginners in Java and i need help for this block:

The problem i have here is, when the number is less than 6 in the first "if" statement, it dont get add to the score at the end. I know the wrong thing i'm doing is in the second "if" statement, i initialize the score to 0, but how i can do so both of the "if" statement can be added to the score when it's higher than 6 and NOT added when it's less than 6? When the random number is less than 6, it shouldn't be added to the score. I don't know if i'm explaning well, but thank you for your time!

int shot;
    int score = 0;
    shot = rand.nextInt(11);
    score += shot;

    if (shot > 6) {

        System.out.print("\nSHOT " + a + ".... Challenger shoots: " + shot);

        }
        else { 
            score = 0;
            System.out.print("\nSHOT " + a + ".... Challenger shoots: " +  "You missed the board!");
        }

    shot = rand.nextInt(11);
    score += shot;
    if (shot > 6) {
    System.out.print("\nSHOT " + (++a) + ".... Challenger shoots " + shot);
    }
    else {
        score = 0;
        System.out.print("\nSHOT " + (++a) + ".... Challenger shoots: " +  "You missed the board!");

    }

    System.out.print("\nCHALLENGER SCORE: " + score);
Arvind Kumar Avinash :

You can do it as

int score = 0;
int shot;

System.out.println("Shot#1:"); 
shot = rand.nextInt(11);
if (shot > 6) {
    score += shot;
    System.out.print("\nSHOT " + a + ".... Challenger shoots: " + shot);
} else {
    System.out.print("\nSHOT " + a + ".... Challenger shoots: You missed the board!");
}

System.out.println("Shot#2:"); 
shot = rand.nextInt(11);
if (shot > 6) {
    score += shot;
    System.out.print("\nSHOT " + (++a) + ".... Challenger shoots: " + shot);
} else {
    System.out.print("\nSHOT " + (++a) + ".... Challenger shoots: You missed the board!");
}

System.out.print("\nCHALLENGER SCORE: " + score);

Feel free to comment in case of any doubt/issue.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=393776&siteId=1