Search code examples
javaarraysbufferedreader

Find the largest and smallest element in arrayList from a typed in BufferedReader


I don't know why im not geeting the smallest number. The larget number is correct if eg.try: 129, 2, 3.

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    int list[] = new int[3];
    int min = list[0];
    int max = list[0];
    int input;

    for (input = 0; input < list.length; input++) {
        String s = reader.readLine();
        list[input] = Integer.parseInt(s);

        if (list[input] < min) {
            min = list[input];
        } else if (list[input] > max) {
            max = list[input];
        }
    }

    System.out.println("Smallet nummber: " + min);
    System.out.println("Biggest nummber: " + max);
}

Solution

  • Just initialize your min and max like this:

    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    

    Also change condition part to this:

    if (list[input] < min) {
        min = list[input];
    }
    if (list[input] > max) {
        max = list[input];
    }
    

    When you are initializing with list[0], min and max both will be initialized with 0. Now if you give input value less than 0, then only min value will be updated. Otherwise, min value will never be updated.