I want to take an integer and get its ordinal, i.e.:
1 -> \"First\"
2 -> \"Second\"
3 -> \"Third\"
...
private static String getOrdinalIndicator(int number) {
int mod = number;
if (number > 13) {
mod = number % 10;
}
switch (mod) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
Another solution
public static String ordinal(int i) {
int mod100 = i % 100;
int mod10 = i % 10;
if(mod10 == 1 && mod100 != 11) {
return i + "st";
} else if(mod10 == 2 && mod100 != 12) {
return i + "nd";
} else if(mod10 == 3 && mod100 != 13) {
return i + "rd";
} else {
return i + "th";
}
}
Pro: does not require an array to be initialized (less garbage)
Con: not a one-liner...
I got a long, complicated one but easy to understand the concept
private static void convertMe() {
Scanner in = new Scanner(System.in);
try {
System.out.println("input a number to convert: ");
int n = in.nextInt();
String s = String.valueOf(n);
//System.out.println(s);
int len = s.length() - 1;
if (len == 0){
char lastChar = s.charAt(len);
if (lastChar == '1'){
System.out.println(s + "st");
} else if (lastChar == '2') {
System.out.println(s + "nd");
} else if (lastChar == '3') {
System.out.println(s + "rd");
} else {
System.out.println(s + "th");
}
} else if (len > 0){
char lastChar = s.charAt(len);
char preLastChar = s.charAt(len - 1);
if (lastChar == '1' && preLastChar != '1'){ //not ...11
System.out.println(s + "st");
} else if (lastChar == '2' && preLastChar != '1'){ //not ...12
System.out.println(s + "nd");
} else if (lastChar == '3' && preLastChar != '1'){ //not ...13
System.out.println(s + "rd");
} else {
System.out.println(s + "th");
}
}
} catch(InputMismatchException exception){
System.out.println("invalid input");
}
}
Best and Simple way, Here we go:
import java.util.*;
public class Numbers
{
public final static String print(int num)
{
num = num%10;
String str = "";
switch(num)
{
case 1:
str = "st";
break;
case 2:
str = "nd";
break;
case 3:
str = "rd";
break;
default:
str = "th";
}
return str;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
System.out.print(number + print(number));
}
}
public static String getOrdinalFor(int value) {
int tenRemainder = value % 10;
switch (tenRemainder) {
case 1:
return value+"st";
case 2:
return value+"nd";
case 3:
return value+"rd";
default:
return value+"th";
}
}
In 1 line:
public static String ordinal(int i) {
return i % 100 == 11 || i % 100 == 12 || i % 100 == 13 ? i + "th" : i + new String[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[i % 10];
}