【问题标题】:Java, Checking to see if two char arrays are equalJava,检查两个字符数组是否相等
【发布时间】:2020-05-05 04:57:03
【问题描述】:

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

如何判断两个数组是否相等?

【问题讨论】:

  • 你能为 orig_team 和 mix_team 提供一些示例输入吗?
  • @Jeremy,我已经放了样本数据。 mix_team 基本上是 orig_team 的改组版本。
  • 呸;如果if 条件退出,则不需要else

标签: java


【解决方案1】:

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

if (Arrays.equals(mix_team, orig_team))

...永远是false

【讨论】:

    【解决方案2】:

    你基本上有以下循环:

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

    while 循环内的代码只有在 something 的计算结果为 true 时才会运行。因此,!something 的值将始终为 false,if 语句的内容将不会运行。

    请尝试:

    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 循环之前声明扫描程序(基本上将初始化行向上移动两行)。

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 2014-06-28
      相关资源
      最近更新 更多