-1

So I have this line of code:

public static void main(String[] args) {
    
    System.out.print("Enter a year: ");
    int a = 1004;    //a = 1004
    System.out.print("Enter another year: ");
    int b = 2020;    //b = 2020
    int min = a < b ? a : b;
    int max = a < b ? b : a;
    System.out.print("Output: ");
    for (int i = min; i <= max; i++) {
    if (i%4==0 && i%100 !=0) {
        System.out.print(i + ", ");  //Output: 1004, 1008, 1012, 1016, 2020,
    }
}
    
}

So the code will print out: Output: 1004, 1008, 1012, 1016, 1020,

How do I remove the last comma and replace it with a dot ?

TgD
  • 15
  • 5
  • I believe this question is not a duplicate of the QA the question has been closed-duplicate with. That question seems to be about enhanced for loops, which this is not – ControlAltDel Aug 22 '22 at 16:26

2 Answers2

0

public static void main(String[] args) {

System.out.print("Enter a year: ");
int a = 1004;    //a = 1004
System.out.print("Enter another year: ");
int b = 2020;    //b = 2020
int min = a < b ? a : b;
int max = a < b ? b : a;
System.out.print("Output: ");
for (int i = min; i <= max; i++)
{
    if (i==b)
    {
        System.out.print(b + ".");
        break;
    }
    if (i%4==0 && i%100 !=0 ) 
    {
       System.out.print(i + ", ");  //Output: 1004, 1008, 1012, 1016, 2020.
     }

}

}

0

just replace this line in your original code:

        System.out.print(i + ", ");  //Output: 1004, 1008, 1012, 1016, 2020,

with this:

        System.out.print(i + ((max-i) > 4? ", ":". ")) ;  //Output: 1004, 1008, 1012, 1016, 2020.
pref
  • 1,651
  • 14
  • 24