public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How old are you?");
int age = sc.nextInt();
System.out.println("What is your favorite number?");
int favnum = sc.nextInt();
int max, min;
String sequence ="";
if (favnum > age) {
max = favnum;
min = age;
} else {
max = age;
min = favnum;
}
System.out.print("The values between " + max + " and " + min + " that are divisible by 4 are ");
for (int i = max; i >= min; i--) {
if (i % 4 == 0) {
System.out.print(i+ ", ");
}
if(i % 4 == 0 && i / 4 == 1) {
System.out.print("and "+ i +".");
}
}
}
}
For example if input values are between 21 and 6. I want it to print "The values between 21 and 6 that are divisible by 4 are 20, 16, 12 and 8. for the last digit to have an and and a period at the end.
This is a small part of my code, but I’ve been stuck on this part I tried many ways to do it but it doesn’t work for me.
This is what it prints:
How old are you?
21
What is your favorite number?
6
The values between 21 and 6 that are divisible by 4 are 20, 16, 12, 8,
What I want it to print:
The values between 21 and 6 that are divisible by 4 are 20, 16, 12 and 8.
>Solution :
int counter=0; //add this counter
System.out.println("How old are you?");
int age = sc.nextInt();
System.out.println("What is your favorite number?");
int favnum = sc.nextInt();
int max, min;
String sequence ="";
if (favnum > age) {
max = favnum;
min = age;
} else {
max = age;
min = favnum;
}
System.out.print("The values between " + max + " and " + min + " that are divisible by 4 are ");
for (int i = max; i >= min; i--) {
if(i % 4==0) {
counter++; //Number of values that are divisible by 4.
}
}
for (int i = max; i >= min; i--) {
if(i % 4 == 0 && counter==1) {
System.out.print("and "+ i +".");
}else
{
if (i % 4 == 0) {
System.out.print(i+ ", ");
counter--;
}
}
}