Java, Checking to see if two char arrays are equal

后端 未结 2 1141
无人共我
无人共我 2020-12-11 13:41

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:<

相关标签:
2条回答
  • 2020-12-11 14:16

    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.

    0 讨论(0)
  • 2020-12-11 14:27

    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).

    0 讨论(0)
提交回复
热议问题