Reputation: 752
I am a Java student and I am having trouble with nesting the conditional statement of this program
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
......
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? thank you
Upvotes: 0
Views: 2820
Reputation: 29
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("");
}
}
}
Upvotes: 0
Reputation: 393936
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
).
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();
}
}
Upvotes: 2