sameTbh
sameTbh

Reputation: 175

String index out of Range: 2 No idea why this is appearing

import java.util.Scanner;
class example{

static String next(String base, String n){

    for(int i= n.length(); i>=0; i--){
        //i= n.length()-1;
        char digit= n.charAt(i);
        int pos= base.indexOf(digit);

        if(pos == base.length()-1){

            n= n.substring(0,i+1)
            + base.charAt(0);
        }//if end

        else{

            n= n.substring(0,i)
            + base.charAt(pos+1);

            break;
        }//else end

    }//for end

    return n;   

}//next end

    public static void main(String[] args){

        System.out.print("Enter the Base: ");
        Scanner input= new Scanner(System.in);
        String base= input.nextLine(); //base number
        System.out.print("Enter Starting Number: ");
        String n= input.nextLine(); // starting number
        //System.out.print("Enter the Last Number: ");
        //String m= input.nextLine(); //last number

        System.out.println(next(base,n));

}//main end
}//class end

When I enter base 0123456789 and the number "12" it should give me "13" since it's going one POS up of the base, but instead it give me this error if I add it in the for loop.

If I get rid of the for loop and the if statement it works fine.

Upvotes: 0

Views: 59

Answers (2)

Abdelhak
Abdelhak

Reputation: 8387

Try to use n.length()-1 instead of n.length() like this:

   for(int i= n.length()-1; i>=0; i--){

Of course the index of n string start from 0 to n.length()-1 not to n.length().

Upvotes: 3

Maljam
Maljam

Reputation: 6274

Java is a 0-indexed language, meaning the last index of an array or a string is length-1. So you should replace:

for(int i= n.length(); i>=0; i--)

by:

for(int i= n.length()-1; i>=0; i--){

Upvotes: 5

Related Questions