vipulnj
vipulnj

Reputation: 135

Both '==' operator and Equals/compareTo method not working

I am trying to accept an array of numbers and output if the the numbers entered are distinct or not. I checked the earlier questions regarding this:

1)using '==' operator doesn't give me the correct output i.e. if the enter "2,3,4" as the command line arguments (inputs), it still returns that the "numbers are not distinct". The program could be compiled and runs in this case, but doesn't give the correct output.

2) using the 'equals' and 'compareTo' methods returns an error while compiling that, "int cannot be dereferenced!" The complilation itself is not successful here.

My code is as follows:

class DistinctNoCheck
{
    public static void main(String[] args)
    {   int temp = 0;
        int [] a = new int [10];
        for(int i=0;i<args.length;i++)
        {
            a[i] = Integer.parseInt(args[i]);
        }
        for(int i=0;i<a.length;i++)
        {
            temp = a[i];
            for(int j=0;j<a.length;j++)
            {
                if((a[j] == temp) && (!(i == j)))
                {
                    System.out.println("Numbers are not distinct!");
                    System.exit(0);
                }
            }
        }
        System.out.println("Numbers are distinct!");
    }
}

Upvotes: 1

Views: 95

Answers (1)

Aniket Thakur
Aniket Thakur

Reputation: 69035

You are using a.length which is 10. You should use args.length while iterating over the array.

Replace

for(int j=0;j<a.length;j++)

with

for(int j=0;j<args.length;j++)

Same goes for loop with i variable.

Upvotes: 2

Related Questions