Search code examples
javaarraysfor-loopvoid

The method should print the array elements between the indexes a and b including a and not including b in line 1


I don't know how to finish this code. Help someone.

package com.telukhin.hw4;

import java.util.Arrays;
public class Task10 {
    public static void main(String[] args) {
        int[] arr = new int[10];
        list(arr, 2, 5);
    }
    private static void list(int[] arr, int a, int b) {
        if (a >= 0 && b <= arr.length) {
            for (int i = a; i < arr[b - 1]; i++) {
                System.out.println(Arrays.toString(arr));
            }
        } else {
            System.out.println("unknown");
        }
    }
} // 

Solution

  • First of all, your array is empty. Take a look at the code below. In the for loop I'm checking that the index is between param a and b (including a, excluding b), and simply printing out the current index.

     public static void main(String[] args) {
        int[] arr = new int[10];
        arr[0] = 0;
        arr[1] = 1;
        arr[2] = 2;
        arr[3] = 3;
        arr[4] = 4;
        arr[5] = 5;
    
        list(arr, 2, 5);
    }
    
    private static void list(int[] arr, int a, int b) {
        if (a >= 0 && b <= arr.length) {
            for (int i = a; i < b; i++) {
                System.out.println(arr[i]);
            }
        } else {
            System.out.println("unknown");
        }
    }