0
我想做一個程序,其中用戶可以輸入一個字符串,它將被轉換爲一個字符數組。該方案有三個功能:我無法確定在我的程序中的java.lang.ArrayIndexOutOfBoundsException的原因
- 的toString():返回char數組作爲字符串再次
- isFull():檢查該數組已滿
- 追加():允許用戶輸入另一個字符
我認爲我的代碼大部分都是正確的方式,但我似乎無法得到append()的工作。這裏是我的代碼:
import java.util.Arrays;
import java.util.Scanner;
public class CharSeq {
private static Scanner sc = new Scanner(System.in);
private static final int maxLength = 5;
private static char[] cArray = new char[maxLength + 1];
private static String input;
private static char append, yesNo;
private static int cLength = 0;
public static void main(String[] args) {
CharSeq cs = new CharSeq();
System.out.println("Input sequence: ");
input = sc.next();
cArray = input.toCharArray();
cLength = cArray.length;
System.out.print(cs.toString());
System.out.print(" (space left: " + (maxLength - cLength) + ")");
cs.append(yesNo, append);
System.out.println(cs.toString());
}
public String toString(){
String s = "";
for(int i = 0; i < cLength; i++){
s = s + cArray[i];
}
return s;
}
public boolean isFull(){
if(cLength == maxLength){
return true;
}
else{
return false;
}
}
public void append(char a, char c){
if(isFull()){
System.out.println("\nCharSeq is full.");
}
else{
System.out.println("\nDo you want to add sequence? [Y/N]");
a = sc.next().charAt(0);
if(a == 'Y' || a == 'y'){
System.out.println("Input sequence: (space left: " + (maxLength - cLength) + ")");
c = sc.next().charAt(0);
cArray[++cLength] = c;
}
}
}
}
這裏的堆棧跟蹤:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at CharSeq.append(CharSeq.java:53)
at CharSeq.main(CharSeq.java:22)
包括堆棧跟蹤,看看它異常報告。 – Alfabravo
'cArray [++ cLength] = c;' – Satya
堆棧跟蹤不僅顯示源中的確切位置,還顯示超出界限的索引值。對程序的簡短介紹通常足以查明原因。如果沒有,調試器就是你的朋友。 – Henry