开发者

Convert number to rank - Java

Does anyone know of a way to convert numbers into their c开发者_如何学Corresponding ranks in Java?

For example:

1 => first

2 => second

11 => eleventh

37 => thirty-seventh

etc..


You are looking for the ordinal.

I'm not aware of any libraries, but have a look at:

How to get the ordinal suffix of a number for many languages in Java or Groovy

or

http://www.javalobby.org/forums/thread.jspa?threadID=16906&tstart=0


You could use the code from this to change the numbers into words. After it you would have to something like this:

String numberAsWord =  EnglishNumberToWords.convert()     //The Method from the site
String numberAsRank = null;
if(numberAsWord.equals("one){
numberasRank = "first";
}else if(numberAsWord.equals("two"){
...
}else{
numberasRank = numberAsWord + "th"
}


Create a Map like this:

Map<Integer, String> ranks = new HashMap<Integer, String>();
ranks.put(1, "first");
ranks.put(2, "second");
...
ranks.put(11, "eleventh");

Then when you need it you can ask for it by doing this:

int number = 1;
System.out.println("The corresponding rank for " + number + " is: " + ranks.get(number));


The easiest way is to do it as Alfredo suggests. It's tedious and would only work up to some upper limit (which is when you get tired of hard-coding in values).

Otherwise you're going to have to program in a general algorithm for this. A good starting point would be reading this: http://home.comcast.net/~igpl/NWA.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜