gpt4 book ai didi

java - 如何修复索引超出范围错误?

转载 作者:行者123 更新时间:2023-11-30 03:14:46 25 4
gpt4 key购买 nike

我是一名初学者java程序员,我正在尝试编写一个程序,将字符串按字母顺序排序,这段代码很困惑,但是当它消除一半字符串时,我收到了超出索引范围的错误。我确信这是由于 i 增加而 l 减少造成的,但我不确定是否有解决办法,我们将不胜感激,并且不允许我使用排序功能。

import java.util.Scanner;
import java.util.ArrayList;

public class Question6{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter a string");
String user = in.nextLine();
int l = user.length();
//System.out.println(l);
int i = 0;
System.out.println("Length is " + user.length());
ArrayList<Character> chars = new ArrayList<Character>();
//System.out.println(first);
while (l > 0){
char first = user.charAt(0);
ArrayList<Character> earliest = new ArrayList<Character>();
earliest.add(first);
char char1 = user.charAt(i);
if (char1 <= earliest.get(0)){
earliest.remove(0);
earliest.add(char1);
user = user.substring(0, i) + user.substring(i+1);
chars.add(char1);
System.out.println("earliest in loop " + earliest.toString());
System.out.println("chars in loop " + chars.toString());
System.out.println("string is now " + user);
System.out.println(" ");
i = i+1;
}
else{
chars.add(first);
System.out.println("chars in else " + chars.toString());
i = 0;
}
l = user.length();
}

System.out.println("done ");
}
}

错误是

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(Unknown Source)
at Question6.main.(Question6.java:19)

这是使用字符串“Stack”作为输入

最佳答案

java.lang.String实现java.lang.Comparable ,所以你可以这样做:

if (s1.compareTo(s2) < 0) {
//...
} else if (s1.compareTo(s2) == 0) {
//...
} else {
// ...
}

此外,在循环 Collection 时避免使用 remove(int),最好使用如下的 Iterator:

Iterator<String> ite = myListString.iterator();
String str;
while(ite.hasNext()) {
str = ite.next();
if (/* this entry has to be removed from the list */) {
ite.remove();
}
}

关于java - 如何修复索引超出范围错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32907434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com