java - Run-time error. Integer convert to string -
i creating program returns ordinal form of number (1st, 2nd etc.). when run program runtime error.
i suspecting has converting int string, can't seem find source of 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 @ java.lang.string.charat(string.java:646) @ stringtraining.ordinalform(stringtraining.java:17) @ stringtraining.run(stringtraining.java:11) @ acm.program.program.runhook(program.java:1568) @ acm.program.program.startrun(program.java:1557) @ acm.program.appletstarter.run(program.java:1895) @ java.lang.thread.run(thread.java:745)
edit:
you calling method number 5 parameter :
ordinalform(5);
the first instruction executes in ordinalform
function :
string number = integer.tostring(num);
this converts variable num
(equals 5) string. number
equal "5". notice number.length()
equal 1 now.
next in condition:
if((number.charat(number.length()-2)=='1' && ....) { }
number.length()
equal 1 (number == "5"). therefore, number.length() - 2
equal -1. technically, trying is:
if((number.charat( -1 )=='1' && ....) { }
and since there no such thing index -1, stringindexoutofboundsexception
thrown, , execution fails.
Comments
Post a Comment