I am currently creating a program that returns the ordinal form of a number (1st, 2nd etc.). But when I run my program I get a runtime error.
I am suspecting that it has something to do with my converting from int to string, but I can't seem to find the source of the problem.
public void run() {
ordinalform(5);
}
private String ordinalform(int num) {
String number = Integer.toString(num);
String correctWord ="";
if((number.charAt(number.length()-2)=='1'
&& number.charAt(number.length()-1)=='1')){
correctWord=number+"th";
} else if (number.charAt(number.length()-2)=='1'
&& number.charAt(number.length()-1)=='2') {
correctWord=number+"th";
} else if ((number.charAt(number.length()-1)=='1'
&& number.charAt(number.length()-1)=='3')) {
correctWord=number+"th";
} else if(number.charAt(number.length()-1)=='1') {
correctWord=number+"st";
} else if(number.charAt(number.length()-1)=='2') {
correctWord=number+"nd";
} else if(number.charAt(number.length()-1)=='3') {
correctWord=number+"rd";
} else {
correctWord=number+"th";
}
println(correctWord);
return correctWord;
}
}
The error: Exception in thread "Thread-1" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.charAt(String.java:646)
at StringTraining.ordinalform(StringTraining.java:17)
at StringTraining.run(StringTraining.java:11)
at acm.program.Program.runHook(Program.java:1568)
at acm.program.Program.startRun(Program.java:1557)
at acm.program.AppletStarter.run(Program.java:1895)
at java.lang.Thread.run(Thread.java:745)