gpt4 book ai didi

java - 我如何嵌套这个条件语句? java 语

转载 作者:行者123 更新时间:2023-12-02 04:20:01 27 4
gpt4 key购买 nike

我是一名 Java 学生,我在嵌套该程序的条件语句时遇到问题

Exercise CozaLozaWoza (Loop & Condition): Write a program called CozaLozaWoza which prints the numbers 1 to 110, 11 numbers per line. The program shall print "Coza" in place of the numbers which are multiples of 3, "Loza" for multiples of 5, "Woza" for multiples of 7, "CozaLoza" for multiples of 3 and 5, and so on. The output shall look like:

1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11 
Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22
23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza
......

我设法做到了

public class CozaLozaWoza {
public static void main(String[] args) {
for (int x = 1; x <= 110; x +=1) {
if (x % 3 == 0) {
System.out.print(" Coza");
}else if (x % 5 == 0) {
System.out.print(" Loza");
}else if (x % 7 == 0) {
System.out.print(" Woza");
}else if (x % 3 != 0 && x % 5 != 0 && x % 7 != 0) {
System.out.print(" " + x);
}


if (x % 11 == 0) {
System.out.println();
}


}
}

}

我无法合并最后一个 if 语句,有人可以帮助我吗?谢谢

最佳答案

if 语句应该相互独立,因为对于同一个数字,多个语句可能为真(例如 “CozaLoza”表示 3 和 5 的倍数)。

for (int x = 1; x <= 110; x +=1) {
boolean regular = true;
System.out.print (" ");
if (x % 3 == 0) {
System.out.print("Coza");
regular = false;
}
if (x % 5 == 0) {
System.out.print("Loza");
regular = false;
}
if (x % 7 == 0) {
System.out.print("Woza");
regular = false;
}
if (regular) {
System.out.print(x);
}
if (x % 11 == 0) {
System.out.println();
}
}

关于java - 我如何嵌套这个条件语句? java 语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32886782/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com