我在Java中有两个字符数组:
orig_array
和mix_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);
}
}
如何确定两个数组是否相等?
答案 0 :(得分:3)
while
循环的块仅在两个数组不相等时执行,因此使用相同的相等性检查启动该块是没有意义的。换句话说,行:
if (Arrays.equals(mix_team, orig_team))
...始终为false
。
答案 1 :(得分: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
循环之前声明扫描器(基本上将初始化行向上移动两行)。