mmir
mmir

Reputation: 11

Why isn't the last number printing?

For some reason, the last number left in the Arraylist won't print and I can't figure out why.Little help please. This is the result [88, 10, 6, 4, 2]

package com.company;

import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(4);
        list.add(2);
        list.add(6);
        list.add(1);
        list.add(88);
        list.add(10);

        ArrayList<Integer> tmp = new ArrayList<>();
        int tmpNum = list.get(0);
        int index = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) >= tmpNum) {
                index = i;
                tmpNum = list.get(i);
            }

            if (i == list.size() - 1) {
                tmp.add(tmpNum);
                list.remove(index);
                i = 0;
                index = 0;
                tmpNum = list.get(0);
            }
        }
        System.out.println(tmp);
    }
}

Upvotes: 1

Views: 77

Answers (1)

Eran
Eran

Reputation: 393771

Add

tmp.add(tmpNum);

after the loop to add the last number.

    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) >= tmpNum) {
            index = i;
            tmpNum = list.get(i);
        }

        if (i == list.size() - 1) {
            tmp.add(tmpNum);
            list.remove(index);
            i = 0;
            index = 0;
            tmpNum = list.get(0);
        }
    }
    tmp.add(tmpNum);
    System.out.println(tmp);

Output:

[88, 10, 6, 4, 2, 1]

The reason the last number wasn't added is that once list contains just the final element (after the last time you call list.remove(index)), you set i to 0, but then the loop's i++ increments it to 1, so the loop ends without adding the last number to tmp.

An alternative solution:

for (int i = 0; i < list.size(); i++) {
  System.out.println (list.size());
    if (list.get(i) >= tmpNum) {
        index = i;
        tmpNum = list.get(i);
    }

    if (i == list.size() - 1) {
        System.out.println ("add " + tmpNum);
        tmp.add(tmpNum);
        System.out.println ("remove " + list.get (index));
        list.remove(index);
        i = -1; // this will cause the loop's i++ to set i to 0
        index = 0;
        tmpNum = Integer.MIN_VALUE; // since you need to find the max remaining number
    }
}

Upvotes: 1

Related Questions