Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run-time error. Integer convert to string

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)


1 Answers

EDIT:

You are calling your method with the number 5 as a parameter :

ordinalform(5);

The first instruction that executes in the ordinalform function :

String number = Integer.toString(num);

This converts the variable num (equals 5) to a String. Now number is equal to "5". Notice that number.length() is equal to 1 now.

Next in your condition:

if((number.charAt(number.length()-2)=='1' && ....) { }

number.length() is equal to 1 (number == "5"). Therefore, number.length() - 2 will be equal to -1. So technically, what you are trying to do is:

if((number.charAt( -1 )=='1' && ....) { }

And since there is no such thing as index -1, a StringIndexOutOfBoundsException is thrown, and the execution fails.

like image 103
Mohammed Aouf Zouag Avatar answered Mar 25 '26 18:03

Mohammed Aouf Zouag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!