0

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

orig_arraymix_array。我需要检查它们是否不相等。

这是我到目前为止所拥有的:

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

如何确定两个数组是否相等?

4

2 回答 2

3

循环的while块仅在两个数组相等时执行,因此以相同的相等性检查开始该块是没有意义的。换句话说,该行:

if (Arrays.equals(mix_team, orig_team))

……永远都是false

于 2013-03-10T03:33:14.653 回答
2

你基本上有以下循环:

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

循环内的代码只有在评估为while时才会运行。因此, 的值将始终为 false,并且语句的内容将不会运行。somethingtrue!somethingif

相反,请尝试:

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(基本上将初始化行向上移动两行)。

于 2013-03-10T03:33:43.830 回答