gpt4 book ai didi

java - 字符串索引超出范围 : 2 No idea why this is appearing

转载 作者:行者123 更新时间:2023-12-01 07:03:05 24 4
gpt4 key购买 nike

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 语句,它就可以正常工作。

最佳答案

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

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

作者:

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

关于java - 字符串索引超出范围 : 2 No idea why this is appearing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35981484/

24 4 0
文章推荐: scala - 如何在scala的foreach中执行操作?
文章推荐: php - jQuery:自动刷新 `
`
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com