Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove last comma

public class Main {

  public static void main(String[] args) {

    // positive number
    int number = 6;

    System.out.print("Factors of " + number + " are: ");

    // loop runs from 1 to 60
    for (int i = 1; i <= number; ++i) {

      // if number is divided by i
      // i is the factor
      if (number % i == 0) {
        System.out.print(i + ",");
      }
    }
  }
}

And my output is "1,2,3,6," but i want it like "1,2,3,6"
How can i do that?

No matter what i do it did not worked.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are multiple ways to solve it. In your case since the last 'i' in the loop is always number itself, and it should be on the list since (number%number==0), you can simply do something like this:

public class Main {

  public static void main(String[] args) {

    // positive number
    int number = 6;

    System.out.print("Factors of " + number + " are: ");

    // loop runs from 1 to 60
    for (int i = 1; i < number; ++i) { //< instead of <=, to exclude i==number

      // if number is divided by i
      // i is the factor
      if (number % i == 0) {
        System.out.print(i + ",");
      }
    }
      //in your case
      System.out.print(number);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading