Than Than
Than Than

Reputation: 23

How to display comma if variable results are more than two and "and" in the end of the result?

A code that gives the multiples of 5 in a given number by the user (x,y). If there is none to display, print "NONE". If there is two to display, separate it with "and". And if theres two or more to display, separate it with comma and "and" in the end of it.

System.out.print("Enter first number: ");
int x = new Scanner (System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner (System.in).nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");

for (;x<=y; x++) {  
    if(x%5==0) {
            System.out.printf("%,d ",x);
    }
}

Sample Output:

Enter number: 1
Enter number: 4
The multiples of 5 from 1 to 4: NONE

Sample Output:

Enter number: 8
Enter number: 12
The multiples of 5 from 8 to 12: 10

Sample Output:

Enter number: 1
Enter number: 17
The multiples of 5 from 1 to 17: 5, 10, and 15.

Upvotes: 3

Views: 898

Answers (6)

lotor
lotor

Reputation: 1090

consider stream api, like

IntStream.range(2, 8).mapToObj(Integer::toString).collect(Collectors.joining(", and "))

Upvotes: 0

R4yY
R4yY

Reputation: 132

This is my solution for this:

Scanner scan = new Scanner(System.in);
        System.out.print("Enter first number: ");
        int x = scan.nextInt();
        System.out.print("Enter last number: ");
        int y = scan.nextInt();
        String output = "The multiples of 5 from " + x + " to " + y + " : ";
        for (; x <= y; x++) {
            if (x % 5 == 0) {
                output = output + x + ", ";
            }
        }
        output = output.substring(0,output.length() -5) + " and "+output.substring(output.length() -4, output.length()-2); 
        System.out.println(output);

Upvotes: 1

GitPhilter
GitPhilter

Reputation: 171

EDIT: I edited my answer to match all sizes of the results-ArrayList:

class Main {

    public static void main(String[] args) {
        System.out.print("Enter first number: ");
        int x = new Scanner(System.in).nextInt();
        System.out.print("Enter last number: ");
        int y = new Scanner(System.in).nextInt();
        System.out.print("The multiples of 5 from " + x + " to " + y + " : ");
        ArrayList<Integer> results = new ArrayList<Integer>();
        for (; x <= y; x++) {
            if (x % 5 == 0) {
                results.add(new Integer(x));
            }
        }
        if (results.size() == 0) {
            System.out.println("No results to display.");
        } else if (results.size() == 1) {
            System.out.println(results.get(0));
        }  else {
            for (int i = 0; i < results.size() - 2; i++) {
                System.out.print(results.get(i) + ", ");
            }
            System.out.print(results.get(results.size() - 2));
            System.out.println(" and " + results.get(results.size() - 1));
        }
    }
}

By using the ArrayList, You can store the values and later print them out. The for-loop only prints all elements, but without the last one, which then gets printed with an " and" before it! I hope you understand how this works.

Upvotes: 2

thuva4
thuva4

Reputation: 1225

Try this, Create a conditional base ending char.

     System.out.print("Enter first number: ");
            int x = new Scanner(System.in).nextInt();
            System.out.print("Enter last number: ");
            int y = new Scanner (System.in).nextInt();
            System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");
            if ((x<5 && y<5) || y/5 == x/5) {
                System.out.printf("NONE");
            }
            else {
                while (y > x) {
                    if (x%5==0) {
                        System.out.printf("%d", x);
                        x += 5;
                        if (x < y) {
                            if (x + 5 < y) {
                                System.out.printf(" , ");
                            } else {
                                System.out.printf(" and ");
                            }
                        }
                    } else {
                        x += 1;
                    }
                }
            }

Upvotes: 1

Andrew
Andrew

Reputation: 49606

The comma you use in printf isn't a simple character, it's a part of the pattern %,d.

Format String Syntax

  • If the ',' ('\u002c') flag is given, then the locale-specific grouping separator is inserted by scanning the integer part of the string from least significant to most significant digits and inserting a separator at intervals defined by the locale's grouping size.

You need to move it out of the pattern %d and add a condition to drop a comma for the first matching number.

for (int i = 0; x <= y; x++) {
    if (x % 5 == 0) {
        System.out.printf("%s%d", (i++ == 0 ? "" : ","), x);
    }
}

Or you could write it in a fancy way

String result = IntStream.rangeClosed(x, y)
                         .filter(i -> i % 5 == 0)
                         .mapToObj(Integer::toString)
                         .collect(Collectors.joining(","));
System.out.println(result);

I have shown two working examples that use "," as the only delimiter. It gets a bit trickier for three delimiters ("," and ", and", and " and "). It's a rare case where a switch statement comes in handy.

final List<String> values = IntStream.rangeClosed(x, y)
        .filter(i -> i % 5 == 0)
        .mapToObj(Integer::toString)
        .collect(Collectors.toList());

switch (values.size()) {
    case 0:
        System.out.println("NONE");
        break;
    case 1:
        System.out.println(values.get(0));
        break;
    case 2:
        System.out.println(String.join(" and ", values));
        break;
    default:
        final String last = values.remove(values.size() - 1);
        System.out.println(String.join(", ", values) + ", and " + last);
}

Upvotes: 2

Kevin Cruijssen
Kevin Cruijssen

Reputation: 9326

Let me start with a few tips of your current code. You currently create two Scanners for both your user inputs. It would be best to only create this one, and re-use it. So change:

System.out.print("Enter first number: ");
int x = new Scanner (System.in).nextInt();
System.out.print("Enter last number: ");
int y = new Scanner (System.in).nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");

To:

Scanner scanner = new Scanner (System.in);
System.out.print("Enter first number: ");
int x = scanner.nextInt();
System.out.print("Enter last number: ");
int y = scanner.nextInt();
System.out.print("The multiples of 5 from "+x+ " to " +y+ " : ");

Next, I would advice to make the step into a variable, so it's easier to change later on (or perhaps ask from the user as input as well):

int step = 5;
...
System.out.print("The multiples of "+step+" from "+x+ " to " +y+ " : ");
...
   if(x%step == 0){
      ...

And now onto your actual problem. Let's first analyse what you want:

  • You want the separator for most items to be ", " (base case)
  • You want the separator for the second to last integer in the iteration to be " and "
  • And the final integer doesn't need any separator anymore, since it's the trailing item

Let's now convert these requirements into code:

for(; x<=y; x++){  
    if(x%step == 0){

       // The last `x` that will be printed, is the x where the difference between y and x
       // is smaller than the step-size:
       boolean lastNumber = y-x < step;
       // The `x` for which we want an " and " separator is the second to last item,
       // so the difference between x and y should be smaller than twice the step-size:
       boolean showAnd = y-x < 2*step;
       // And then we can use these two booleans with a simple ternary-if to determine the
       // format we'd want to use in our print:
       System.out.printf(lastNumber ? "%d\n"
                          : showAnd ? "%d and "
                          :           "%d, ",
                         x);
  }
}

Try it online.

Upvotes: 1

Related Questions