检查两个字符数组是否相等

检查两个字符数组是否相等

本文介绍了Java,检查两个字符数组是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有两个字符数组:

I have two character arrays in Java:

orig_array mix_array .我需要检查它们是否相等.

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?

推荐答案

您基本上具有以下循环:

You essentially have the following loop:

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

仅当 something 评估为 true 时, while 循环内的代码才会运行.因此,!something 的值将始终为false,并且不会运行 if 语句的内容.

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.

相反,请尝试:

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


顺便说一句,您不必每次都创建扫描仪.更好的方法是在 while 循环之前声明扫描程序(基本上将初始化行上移两行).


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

这篇关于Java,检查两个字符数组是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:32