Home > Back-end >  Remove a trailing comma in java
Remove a trailing comma in java

Time:11-13

int number = 4;

while(number <= 100)
{
   System.out.println(number   ",");
   number  = 2;
}

I tried to do it myself but couldn't I search the internet but only found removing commas for Strings only I need to lose the last comma at 100

CodePudding user response:

You cannot remove characters from System.out that you already printed. Instead of trying to remove the last comma, do not print it in the first place. E.g.

int number = 4;
while (number < 100) {
  System.out.println(number   ",");
  number  = 2;
}
System.out.println(number   "");
number  = 2; // this increment is only necessary depending on what you do after the loop

Note the adjusted condition in the loop.

CodePudding user response:

int number = 4;

while(number <= 100)
{
  if(number > 4) {
    System.out.print(",");
  }

  System.out.println(number);
  number  = 2;
}
  • Related