user1471980
user1471980

Reputation: 10646

Java, Checking to see if two char arrays are equal

I have two character arrays in Java:

orig_array and mix_array. I need to check if they are not equal.

Here is what I have so far:

sample data
orig_team=one
mix_team=neo

while(!Arrays.equals(mix_team, orig_team))
{

    if (Arrays.equals(mix_team, orig_team))
    {

        System.out.println("congradulations! you did it");
        System.exit(0);
    }

    else {

        System.out.println("enter the index");
        Scanner scn = new Scanner(System.in);
        int x = scn.nextInt();
        int y = scn.nextInt();
        char first=mix_team[x];
        char second=mix_team[y];
        mix_team[x]=second;
        mix_team[y]=first;
        for (int i = 0; i < mix_team.length; i = i + 1) 
        {
            System.out.print(i);  
            System.out.print(" ");
        }
        System.out.println();
        System.out.println(mix_team);
    }
}       

How can I determine if the two arrays are equal?

Upvotes: 0

Views: 7758

Answers (2)

wchargin
wchargin

Reputation: 16047

You essentially have the following loop:

while (something) {
    if (! something) {
        code();
    }
}

The code inside the while loop will only run if something evaluates to true. Thus, the value of !something will always be false, and the if statement's contents will not be run.

Instead, try:

while (!Arrays.equals (mix_team, orig_team)) {
    System.out.println("enter the index");
    Scanner scn = new Scanner(System.in);
    int x = scn.nextInt();
    int y = scn.nextInt();
    char first=mix_team[x];
    char second=mix_team[y];
    mix_team[x]=second;
    mix_team[y]=first;
    for (int i = 0; i < mix_team.length; i = i + 1) 
    {
        System.out.print(i);  
        System.out.print(" ");
    }
    System.out.println();
    System.out.println(mix_team);
}
System.out.println("congratulations! you did it");
System.exit(0);

By the way, you don't need to create a scanner each time. A better way to do it would be to declare the scanner before the while loop (basically move the initialization line up two lines).

Upvotes: 2

Wayne
Wayne

Reputation: 60424

The while loop's block is only executed when the two arrays are not equal, so starting that block with the same equality check makes no sense. In other words, the line:

if (Arrays.equals(mix_team, orig_team))

...will always be false.

Upvotes: 3

Related Questions