cod*_*nja 0 java indexoutofboundsexception
有人可以告诉我为什么.toCharArray()行给出了一个Index Out of Bounds异常吗?为什么它甚至为String提供索引0大小为0的异常?我还没有定义一个字符串数组?!
此外,此代码应该在O(n)时间运行吗?
import java.util.ArrayList;
import java.util.List;
public class FirstNonRepeating {
public static List<Character> list = new ArrayList<Character>();
public static List<Character> list2 = new ArrayList<Character>();
public static String res(String x) {
char[] y = x.toCharArray();
for(char c:y){
list2.add(c);
if(list.contains(c)){
list2.remove(c);
}
else{
list2.add(c);
}
}
if(list2.isEmpty()){
return "NONE";
}
else return (""+list.get(0));
}
public static void main(String[] args) {
String a="Google";
String z=res(a);
System.out.println(z);
}
}
Run Code Online (Sandbox Code Playgroud)
您的例外情况如下:
if (list2.isEmpty()) {
return "NONE";
} else return ("" + list.get(0));
Run Code Online (Sandbox Code Playgroud)
检查空虚list2并尝试获取第一个元素,list其中似乎为空,并抛出异常.将其更改为:
... else return ("" + list2.get(0));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
498 次 |
| 最近记录: |