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

时间:2015-10-01 11:43:55

标签: java

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

  

练习CozaLozaWoza(循环和条件):编写一个名为的程序   CozaLozaWoza打印数字1到110,每行11个数字。   程序应打印“Coza”代替数字   3的倍数,“Loza”为5的倍数,“Woza”为7的倍数,   “CozaLoza”为3和5的倍数,依此类推。输出应该看起来   像:

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语句,任何人都可以帮助我吗?谢谢

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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