Reputation: 59
I am very new to Java and am trying to write a simple code. Here is the description: Write a program that prompts the user for a number X. Print the numbers from 1 to X. However, in place of multiples of 4 print “qqqq”. In place of multiples of 7, print “seven”. If a number is divisible by both 4 and 7 print “qqqqseven”. It means if I input 4, my output should be 1, 2, 3, (qqqq), ...but I get 1(qqqq), 2(qqqq), 3(qqqq), 4(qqqq)..... Can anyone help me and let me know where I am doing wrong? Any help is appreciated. Than you.
public static void main(String args[])
{
//Print Method
System.out.println("Enter number upto which you want to print: ");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
for(int i=1; i <= x; i++)
{
System.out.println(i);
//if x is multiples of 4
if (x % 4 == 0)
System.out.println("qqqq");
//if x is multiples of 7
if (x % 7 == 0)
System.out.println("seven");
//if x is divisible by 4 and 7
if (x % 4 == 0 && x % 7 == 0)
System.out.println("qqqqseven");
}
}
}
Upvotes: 1
Views: 411
Reputation: 8499
The idea here is to use the if condition from most specific to least specific. In you case the most specific condition is a divisor of 4 and 7, followed by divisor of 4, divisor fo 7 and finally the least specific one which means everything else. If you could arrage your if conditions in that order you'll get the result.
Note: It a good practice to close scanner or any resources that you open. :)
import java.util.Scanner;
public class TestProgram {
public static void main(String[] args) {
System.out.println("Enter number upto which you want to print: ");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
for (int i = 1; i <= x; i++) {
if(i%4 == 0 && i%7 == 0) {
System.out.println("qqqqseven");
} else if(i%4 == 0) {
System.out.println("qqqq");
} else if(i%7 == 0){
System.out.println("seven");
} else {
System.out.println(i);
}
}
input.close();
}
}
Upvotes: 1
Reputation: 3576
Replace
if (x % 4 == 0)
With
if (i % 4 == 0)
Do likewise for the other occurrences of %
To get the correct output for multiple of 28 you will need to modify you code to this:
if (i % 4 == 0 && i % 7 == 0) { // if i is a multiple of 28 (of both 4 & 7)
System.out.println("qqqqseven");
}
else {
if (i % 4 == 0) { // if i is multiples of 4
System.out.println("qqqq");
}
else if (i % 7 == 0) { // if i is multiples of 7
System.out.println("seven");
}
}
Upvotes: 3