0
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.

  • 1
    do not print the last comma (for example always print `1`, loop starting at `2`, and print the comma before the numbers -- or the *opposite* stop looping before `number` and print `number` with comma after the loop -- you can also use a flag to not print the comma for the first number) – user16320675 Nov 15 '22 at 19:26

3 Answers3

1

The simple and robust solution is to store the values in a list, and only then display them. This way you'll easily know when you're printing the last element. Besides, then you could just do something like:

List<String> divisors = new ArrayList<>();

// 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) {
    divisors.add(String.valueOf(i));
  }
}

System.out.println(String.join(",", divisors));
abel1502
  • 955
  • 4
  • 14
1

Solution written by @abel1502 is the simplest if you want to display the values and keep them to use elsewhere. If you just want to display them, then there are more modern ways to do it (if you use a recent version of Java) :

var number = 60;
System.out.println(
    IntStream.rangeClosed(1, number)
        .filter(i -> number % i == 0)
        .mapToObj(String::valueOf)
        .collect(Collectors.joining(","))
);
Junior Dussouillez
  • 2,327
  • 3
  • 30
  • 39
0

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);
  }
}
ATP
  • 2,939
  • 4
  • 13
  • 34