Java,检查两个char数组是否相等

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

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

你基本上有以下循环:

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

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

 if (Arrays.equals(mix_team, orig_team)) 

……永远都是false