Попытка отладки ошибки массива по исключению из границ: 4 - PullRequest
0 голосов
/ 04 ноября 2019

Я пытаюсь добиться такого вида вывода

Введите размер списка 1: 5

Введите элементы в список 1: 1 5 1691 248

Введите размер списка 2: 4

Введите элементы в списке 2: 2 4 5 27

list1 равен 1 5 16 91 248

list2 равен 2 4 5 27

Объединенный список равен 1 2 4 55 16 27 91 248

Что я получаю

Введите размер списка 1: 5

Введите элементыв списке 1: 1 5 16 91 248

Введите размер списка 2: 4

Введите элементы в списке 2: 2 4 5 27

list1 равен 1 5 16 91 248

list2 равен 2 4 5 27 Исключение в потоке "main" java.lang.ArrayIndexOutofBoundsException: 4at MergeTest.main (Mergetest.java:41)

Я закончил писать код, и теперь я потерян, потому что получаю Array indexoutOfBounds Exceptoin: 4 и яуже лвзялись за другие решения, которые сделали люди, и я все еще не понимаю. Кто-то сказал мне, что это может быть частью кода, но я все еще полностью потерян.

(a[firstIndex] <= b[secondIndex])
        {
            c[thirdIndex] = a[firstIndex];
            firstIndex++;
        }
        else
        {
            c[thirdIndex] = b[secondIndex];
            secondIndex++;
        }
        thirdIndex++;
        }"

Вот что у меня есть.

import java.util.Scanner;

public class MergeTest{

public static void main(String[] args){
    int firstLength, secondLength;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter the size of list 1: ");
    firstLength = keyboard.nextInt();
    int a[] = new int[firstLength];
    System.out.println("Enter the items of list 1: ");

    for (int i = 0; i < firstLength; i++)
    {
        a[i] = keyboard.nextInt();
    }

    System.out.print("Enter the size of list 2: ");
    secondLength = keyboard.nextInt();
    int b[] = new int[secondLength];
    System.out.println("Enter the items of list 2: ");

    for (int i = 0; i < secondLength; i++)
    {
        b[i] = keyboard.nextInt();
    }

    System.out.print("list1 is ");

    for (int i = 0; i < firstLength; i++) {
        System.out.print(a[i]);
        System.out.print(" ");
    }

    System.out.println();

    System.out.print("list2 is ");

    for (int i = 0; i < firstLength; i++) {
        System.out.print(b[i]);
        System.out.print(" ");
    }

    System.out.println();

    int thirdLength = firstLength + secondLength;
    int c[] = new int[thirdLength];
    int firstIndex = 0;
    int secondIndex = 0;
    int thirdIndex = 0;
    while (firstIndex < firstLength && secondIndex < secondLength) {

    if (a[firstIndex] <= b[secondIndex])
    {
        c[thirdIndex] = a[firstIndex];
        firstIndex++;
    }
    else
    {
        c[thirdIndex] = b[secondIndex];
        secondIndex++;
    }
    thirdIndex++;
    }
    System.out.print("Here is the output:");
    for (int z = 0; z < thirdLength; z++)
    {
        System.out.print(c[z]);
    }
}

}

Любые отзывы приветствуются.

1 Ответ

0 голосов
/ 04 ноября 2019

Во втором цикле, где вы печатаете второй список, вы используете firstLength. firstLength больше, чем secondLength, поэтому для большего индекса он выбрасывает индекс из привязанного исключения. Использовать secondLength в циклической печати list2.

System.out.print("list2 is ");

for (int i = 0; i < secondLength; i++) {
    System.out.print(b[i]);
    System.out.print(" ");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...