B
B
blessmemary2021-09-16 16:24:07
Java
blessmemary, 2021-09-16 16:24:07

Duplicate values ​​in an array. Where is the mistake?

Help solve the problem, please.
I send 5 lines "a", "b", "c", "d", "e" to the scanner.
Expected outcome : array of 10 lines: aabbccddee
I get: an array with 10 lines: aaaaaabcde

The code is attached below the screenshot.
Thanks in advance!

614344d83a429822259372.png

private static void mySecondTask(){
        Scanner scan2 = new Scanner(System.in);
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            System.out.print("Введите строку: ");
            String elem = scan2.next();
            list.add(elem);
        }
        doubleValues(list);
        for (String s : list) {
            System.out.println("" + s);
        }

    }
    private static void doubleValues(ArrayList<String> lst){
        System.out.println("Я тут");

        int current;
        for (int i = 0; i < 5; i++) {
            System.out.println("Я в цикле");
            current = i;
            System.out.println("Текущий индекс: " + current);
            String value = lst.get(current);
            System.out.println("Текущее значение: " + value);

            lst.add((current+1),value);
            System.out.println("добавил значение "+value+ " под индексом " +(current+1));
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-09-16
@blessmemary

You are modifying the original list, but not making any adjustments for it.
First you take the first character and add it to the second place.
Then you take the second character, but it's not "b" as you would like, but "a" added in the previous step. Etc.
You need to either collect a new list, or remember that you have already inserted some characters. After i insertions, the first non-duplicate character will be at position 2*i and its copy should be inserted at the next (2i+1) position.
Well, or go through the list from the end to the beginning. Then you will refer to the unmodified part.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question