首页 > 解决方案 > 带有 If 语句和随机数的 Java

问题描述

我是 Java 的初学者,我需要这个块的帮助:

我在这里遇到的问题是,当第一个“if”语句中的数字小于 6 时,它不会在最后添加到分数中。我知道我做的错误是在第二个“if”语句中,我将分数初始化为 0,但是当它高于 6 和小于 6 时不添加?当随机数小于 6 时,不应将其添加到分数中。我不知道我是否解释得很好,但谢谢你的时间!

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);

标签: javaif-statementrandom

解决方案


你可以这样做

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);

如有任何疑问/问题,请随时发表评论。


推荐阅读