java - 带有 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);
解决方案
你可以这样做
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);
如有任何疑问/问题,请随时发表评论。
推荐阅读
- google-cloud-platform - gcloud 构建提交时致命:不是 git 存储库
- reactjs - “你不能把(又名从 saga 派发)冻结的动作”——Redux Saga
- python - 我们可以在 django 应用程序中创建单独的视图文件吗?
- ethereum - 待处理的以太坊交易的日志在确认后消失了
- java - Spring batch 2.4.1 + Wildfly 20 final - java.lang.NoSuchFieldError: BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES
- python - 执行不会在 Visual Studio 代码中的机器人文件中的断点处停止
- java - 从摄氏度到华氏度没有得到正确的答案
- c# - 无法为核心 API 中的每个请求调用 GetService
- c++ - 如何检查字符串是否包含未转义的正则表达式控制字符?
- css - 如何在 React-Bootstrap 中放置内联无线电控件?