字符串索引超出范围:2不知道为什么会出现这种情况

时间:2016-03-14 07:11:54

标签: java

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

当我输入基础0123456789和数字“12”时,它应该给我“13”,因为它是基础的一个POS,但是如果我在for循环中添加它会给我这个错误。

如果我摆脱了for循环和if语句,它可以正常工作。

2 个答案:

答案 0 :(得分:5)

Java是一种0索引语言,意味着数组或字符串的最后一个索引是length-1。所以你应该替换:

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

by:

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

答案 1 :(得分:3)

尝试使用n.length()代替 for(int i= n.length()-1; i>=0; i--){ ,如下所示:

0

当然,n字符串的索引从n.length()-1开始到n.length()而不是plyr

相关问题