我正在嘗試使用LinkedLists添加長達5個數字的java應用程序。在運行結束時,我得到這個:IndexOutOfBoundsException錯誤添加長號碼
在線程異常 「主要」 java.lang.IndexOutOfBoundsException:指數: 0,大小:0 在java.util.LinkedList.checkElementIndex(LinkedList.java: 555)在java.util.LinkedList.remove(LinkedList.java:525)在 Assignment1.LongNumbers.remove(LongNumbers.java:33)在 Assignment1.LongNumbers.main(LongNumbers.java:92)
這裏是代碼:
import java.util.*;
/**
*
* @author .....
*/
public class LongNumbers
{
private List<Integer> [] theLists;
public LongNumbers() {
this.theLists = new LinkedList[6];
for (int i=0; i<6; i++)
this.theLists[i]= new LinkedList<>();
}
public void add(int location, int digit) {
//add digit at head of LinkedList given by location
theLists[location].add(digit);
}
public int remove(int location) {
//remove a digit from LinkedList given by location
return theLists[location].remove(location); //LongNumbers.java:33
}
public boolean isEmpty(int location) {
//check for an empty LinkedList given by location
return theLists[location].isEmpty();
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
//Local Variables
int digit;
int carry = 0;
int numberAt = 0;
int largestNumLength = 0;
char[] digits;
String number;
boolean userWantstoQuit = false;
LongNumbers Lists = new LongNumbers();
System.out.println("The program will enter up to 5 numbers and add them up.");
System.out.println();
while(!userWantstoQuit && numberAt != 5){
System.out.print("Enter a number, enter -1 to quit entry phase: ");
number = stdIn.nextLine();
if((number.compareTo("-1")) == 0)
userWantstoQuit = true;
else{
digits = new char[number.length()];
for(int i=0;i<number.length();i++)
digits[i] = number.charAt(i);
for(int i=0;i<number.length();i++){
int tempValue = digits[i] - 48;
try{
Lists.add(numberAt, tempValue);
}
catch(NumberFormatException nfe){
System.out.println("Invalid Input. Please try again.");
break;
}
if(i == (number.length() - 1))
numberAt++;
if(number.length() > largestNumLength)
largestNumLength = number.length();
}
}
}
for(int j=0;j<largestNumLength;j++){
int tempDigit = 0;
int index = 0;
while(index < numberAt){
if(Lists.theLists[index].get(0) != null){
tempDigit += Lists.theLists[index].get(0);
Lists.remove(0); //LongNumbers.java:99
}
index++;
}
digit = carry + tempDigit;
if(j < numberAt){
carry = digit/10;
digit = digit%10;
}
Lists.add(5, digit);
}
System.out.print("The sum of the numbers is: ");
for(int i=0;i<Lists.theLists[5].size();i++){
System.out.print(Lists.theLists[5].get(i));
}
System.out.println();
System.out.println();
System.out.println();
}//end main
}//end class
這將是很好,如果你可以在你的代碼中指示什麼是「LongNumbers.java:33」 – Leo 2014-09-29 21:31:35
對不起。編輯已經完成 – user123456 2014-09-29 21:37:18
你的堆棧跟蹤非常清楚地告訴你,在你的remove()方法中,你要求列表中索引爲0的元素的大小爲零 - 即列表爲空。看看你如何初始化你的列表。 – drewmoore 2014-09-29 21:49:08