Я пытаюсь wrtie java-приложение, которое добавляет до 5 длинных чисел, используя LinkedLists. В конце пробега я получаю это:IndexOutOfBoundsException error добавление длинных чисел
Исключение в потоке "основной" 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
Простите об этом. Сделано редактирование – user123456
Ваша трассировка стека говорит вам совершенно ясно, что в вашем методе 'remove()' вы запрашиваете элемент с индексом 0 списка с нулевым размером - то есть список, который пуст , посмотрите, как вы инициализируете свои списки. – drewmoore