Lily Morris
Lily Morris

Reputation: 27

Using concat with an int? (java)

I am trying to do the following:

If a number between 1 and 100 is entered by the user, then:

Example below is for the input value of 25:

1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th

I can't figure out how to add the: st, nd, rd, th without using concat.

Here is my code:

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);

   int userNum;
  userNum = scnr.nextInt();
  for (int i=1; i<=userNum; i++) {
  System.out.println(i);
    }
  }
}

Is there another way to do this? Thanks.

Upvotes: 2

Views: 314

Answers (3)

th3matr1x
th3matr1x

Reputation: 19

you can do that with printf

for (int i=1; i<=userNum; i++) {
     System.out.printf("%d%s\n",i,i%10==1 && i>19 ? "st " : i%10==2 && i>19 ? "nd " : i%10==3 && i>19 ? "rd " : "th ");
}

Upvotes: 1

sare3th
sare3th

Reputation: 828

You can do it without using concat. You can check if number -st -nd -rd with modulo ( % 10)

import java.util.*;
import java.util.AbstractMap.SimpleEntry;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main {

private static final String DEFAULT_POSTFIX = "th";
private static final Map<Integer, String> POSTFIX_MAP =
        Stream.of(
                new SimpleEntry<>(1, "st"),
                new SimpleEntry<>(2, "rd"),
                new SimpleEntry<>(3, "nt"))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

private static String getPostfix(int number) {
    if (Arrays.asList(11,12,13).contains(number)) return DEFAULT_POSTFIX;
    return Optional
            .ofNullable(POSTFIX_MAP.get(number % 10))
            .orElse(DEFAULT_POSTFIX);
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int userNum = scanner.nextInt();
    IntStream
            .rangeClosed(1, userNum)
            .forEach(it -> System.out.println(it + getPostfix(it)));
}

}

Upvotes: 0

HackerBoss
HackerBoss

Reputation: 829

The special String concatentation operator (+) in Java will automatically convert scalars to strings (when the string is on the left). You could do something like this:

System.out.println(""+i+getPostfix(i));

where getPostfix would return an appropriate postfix for the given integer (-st, -nd, etc). I leave implementation of this function as an exercise.

Upvotes: 1

Related Questions