简体   繁体   English

如何嵌套此条件语句? 在Java中

[英]How can I nest this conditional statement? in Java

I am a Java student and I am having trouble with nesting the conditional statement of this program 我是一名Java学生,并且在嵌套该程序的条件语句时遇到了麻烦

Exercise CozaLozaWoza (Loop & Condition): Write a program called CozaLozaWoza which prints the numbers 1 to 110, 11 numbers per line. 练习CozaLozaWoza(循环和条件):编写一个名为CozaLozaWoza的程序,该程序将打印数字1到110,每行打印11个数字。 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. 程序应打印“ Coza”代替3的倍数,“ Loza”代替5的倍数,“ Woza”代替7的倍数,“ CozaLoza”代替3和5的倍数,依此类推。 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
......

I manage to do this 我设法做到这一点

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


    }
}

} }

I can't merge the last if statement, can anyone help me? 我无法合并最后一个if语句,有人可以帮助我吗? thank you 谢谢

The if statements should be independent of each other, since more than one statement can be true for the same number (for example "CozaLoza" for multiples of 3 and 5 ). if语句应该彼此独立,因为对于同一数字,可以有多个语句为真(例如, "CozaLoza" for multiples of 3 and 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();
    }
}
   package homePrac;

public class LOZAMOZACOZA 
{
    public static void main (String []args)
    {
        int max = 110;
        for (int i=1; i<=max; i++)
        {
            if (i%3==0)
                System.out.print("Coza");
            else if (i%5==0)
                System.out.print ("Woza");
            else if (i%7==0)
                System.out.print("CozaLoza");
            else if (i%3!=0 || i%5!=0 || i%7!=0)
                System.out.print(i);
            if(i%11==0)
                System.out.println("");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM