Edit: I figured out what was wrong, when count hits 5, it stays at 5 until the first condition is hit then count changes. This results in the extra empty lines.
So my goal is for the output to be one line after the other but its not doing that.
public class Main {
public static void main(String[] args) {
int n=10,m=50,a=2,b=3;
int count = 0;
for (int i=n;i<=m;i ){
if(i%a==0&&i%b!=0) {
System.out.print(i " ");
count ;
}
if (count%5==0)
System.out.println();
}
}
}
This code is suppose to take integer values of n, m, a and b and displays all the numbers from n to m that are divisible by a but not divisible by b, and prints the results 5 numbers per line. So far I have got printing the numbers 5 times per line down but every time it out puts the next line, instead of immediately printing to the next line it skips some.
Here is what its suppose to do when n=10, m=50, a=2 and b=3:
10 14 16 20 22
26 28 32 34 38
40 44 46 50
Instead its printing this:
10 14 16 20 22
26 28 32 34 38
40 44 46 50
What am I doing wrong?
CodePudding user response:
When count
reaches a number that's divisible by 5
, you continue iterating over i
. In some of these iterations, count
is not incremented, so it remains divis5
and you continue adding new lines.
Moving the second if
statement inside the for
loop should solve this:
for (int i=n;i<=m;i ){
if(i%a==0&&i%b!=0) {
System.out.print(i " ");
count ;
if (count % 5 == 0) // Here!
System.out.println();
}
}
CodePudding user response:
You forgot to consider that the count variable will not increase as long as you dont satisfy the first if block. The better way is to check if its equal to 5 print new line the set count = 0
public class Main {
public static void main(String[] args) {
int n=10,m=50,a=2,b=3;
int count = 0;
for (int i=n;i<=m;i ){
if(i%a==0&&i%b!=0) {
System.out.print(i " ");
count ;
}
if (count==5){
System.out.println();
count = 0;
}
}
}
}
CodePudding user response:
When the count is 5 and the code is not entered to the first "if" the new line will be printed because the count will not be increased.
Please try:
public class Main {
public static void main(String[] args) {
int n=10,m=50,a=2,b=3;
int count = 0;
boolean is_new_line = false;
for (int i=n;i<=m;i ){
if(i%a==0&&i%b!=0) {
System.out.print(i " ");
count ;
is_new_line = false;
}
if ((count%5==0) && (is_new_line==false)) {
System.out.println();
is_new_line = true;
}
}
}
}