boolean from array - function in java, input from command line

Viewed 125

I have a problem, which read N numbers from the command line, and I want to check if all those numbers are the same.

This is my code

class q2 {
    public static boolean check(int[] arr) { 
        for (int i = 0; i < arr.length-1; i++) {
            for (int j = 1; j < arr.length; j++) {
                if (arr[i]==arr[j]) return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {   
        int[] arr = new int[args.length];
        boolean result = check(arr);
        System.out.println(result);
    }
}

but in any case (but no input at all) it return false and I don't know where is the mistake.

1 Answers

If you are passing the values from the command line, you need to add those values into the array that you will pass into the check method:

public static void main(String[] args) {
    int[] arr = new int[args.length];
    for(int i = 0; i < arr.length; i++){
        arr[i] = Integer.parseInt(args[i]);
    }
    boolean result = check(arr);
    System.out.println(result);
}

You can simplify your check method e.g. you do not need a double loop. Just compare the current element with the next one as shown below:

public static boolean check(int[] arr) {
    for (int i =0;i<arr.length-1;i++)
        if (arr[i] != arr[i + 1])
           return true;
   return false;
}
Related