-2

I'm writing a simple java code that takes two integers as min and max and a third integer as divisor and it finds all numbers between that are divisible by the third integer, which worked fine but in the output I can't get rid of the last comma.

Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the first number: ");
    int a = scanner.nextInt();
    System.out.print("Enter the second number: ");
    int b = scanner.nextInt();
    System.out.print("Enter the divisor: ");
    int d = scanner.nextInt();
    for(int i=a; i<=b; i++) {
        if(i%d == 0)
            System.out.print(i+", ");
    }

How could I do it?

mk-pawn
  • 31
  • 4

5 Answers5

3

I prefer to avoid the issue by writing commas before things where appropriate, and not after. It seems more straightforward to know when you're doing the first thing, compared to knowing when you're doing the last thing.

String sep = ""; // no separator before first print
for (int i=a; i<=b; i++) {
    if (i%d == 0) {
        System.out.print(sep + i);
        sep = ", "; // separator for every following print
    }
}
iggy
  • 1,328
  • 4
  • 3
1

You can use an if statement to print a comma only if it is not the last element.

if(i%d == 0){
    System.out.print(i);
    if(((i/d)+1)*d <= b) System.out.print(", ");
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

You can use as boolean to control printing the comma.

boolean addComma = false;
for (int i=a; i<=b; i++) {
    if (i%d == 0) {
        System.out.print((v ?  "," : "") + i);
        addComma = true;
    }
}
WJS
  • 36,363
  • 4
  • 24
  • 39
1

For these kinds of problems the StringJoiner is especially useful:

StringJoiner out = new StringJoiner(",");
for(int i=a; i<=b; i++) {
    if(i%d == 0)
        out.add(Integer.toString(i));
}
System.out.println(out);
SDJ
  • 4,083
  • 1
  • 17
  • 35
0

You could use substringto strip the space and comma off the end if it is the last number. It is not as elegant as Unmitigated's solution, but it should work:

String validNumbers = "";
for(int i=a; i<=b; i++) {
    if(i%d == 0)
    validNumbers += i + ", ";
}
if (validNumbers != "") {
    validNumbers = validNumbers.substring(0, validNumbers.length() - 2);
}
System.out.print(validNumbers);
burtoja
  • 1
  • 2