System.out.print("请输入参赛天数:"); int n = scanner.nextInt(); int gold = 0, silver = 0, bronze = 0; for (int i = 0; i < n; i++) { System.out.printf("请输入第%d天的奖牌数(金 银 铜):", i + 1); int g = scanner.nextInt(); int s = scanner.nextInt(); int b = scanner.nextInt(); gold += g; silver += s; bronze += b; } int total = gold + silver + bronze; System.out.printf("金牌:%d,银牌:%d,铜牌:%d,总奖牌数:%d\n", gold, silver, bronze, total); 加个n的范围(1≤n≤17)
时间: 2024-02-14 16:17:41 浏览: 64
好的,可以在读取 `n` 的值之后添加如下代码来判断 `n` 是否在范围内:
```java
if (n < 1 || n > 17) {
System.out.println("参赛天数必须在 1 到 17 之间");
return;
}
```
完整代码如下:
```java
import java.util.Scanner;
public class MedalCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入参赛天数:");
int n = scanner.nextInt();
if (n < 1 || n > 17) {
System.out.println("参赛天数必须在 1 到 17 之间");
return;
}
int gold = 0, silver = 0, bronze = 0;
for (int i = 0; i < n; i++) {
System.out.printf("请输入第%d天的奖牌数(金 银 铜):", i + 1);
int g = scanner.nextInt();
int s = scanner.nextInt();
int b = scanner.nextInt();
gold += g;
silver += s;
bronze += b;
}
int total = gold + silver + bronze;
System.out.printf("金牌:%d,银牌:%d,铜牌:%d,总奖牌数:%d\n", gold, silver, bronze, total);
}
}
```
这样,如果输入的 `n` 不在范围内,程序会输出错误提示并直接结束。
阅读全文