找到重复的程序结果不正确。

huangapple go评论80阅读模式
英文:

FindDuplicate program not having right outcome

问题

int a = args.length;
int[] list = new int[a];
for (int i = 0; i < a; i++) {
  int n = Integer.parseInt(args[i]);
  list[i] = n;
}
for (int i = 0; i < a; i++) {
  for (int j = i + 1; j < a; j++) {
    if (list[i] == list[j]) {
      System.out.print("True");
    } else {
      System.out.print("False");
      return;
    }
  }
}

根据我理解的内容,代码看起来没问题,但当我测试了一些值时,出现了我不知道如何解决的问题。例如,对于测试案例 4 5 2 1 2,它输出 false。

英文:

My code is intended to take user input n value for example 1 3 6 6 3 and identify if there's a duplicate number. Print out True if there is one and False otherwise.

int a = args.length;
int[] list = new int[a];
for (int i = 0; i &lt; a; i++) {
  int n = Integer.parseInt(args[i]);
  list[i] = n;
}
for (int i = 0; i &lt; a; i++) {
  for (int j = i + 1; j &lt; a; j++) {
    if (list[i] == list[j]) {
      System.out.print(&quot;True&quot;);
    } else {
      System.out.print(&quot;False&quot;);
      return;
    }
  }
}

The code, in my opinion, looks fine but when I tested a couple of values it's having issues that I don't know how to solve.
For example, for test case 4 5 2 1 2 it prints out false

答案1

得分: 4

你目前正在打印 false,并且在找到两个不相等的数字后返回。其他的数对没有进行比较。

将打印 false 的部分移到代码末尾。

for (int i = 0; i < a; i++) {
    for (int j = i + 1; j < a; j++) {
        if (list[i] == list[j]) {
            System.out.print("True");
            return;
        }
    }
}
System.out.print("False"); // 在检查完所有数对后打印
英文:

You are currently printing false and returning once you find two numbers that are not equal. The other pairs are not compared.

Move printing false to the end of the code.

for(int i = 0; i &lt; a; i++){
    for(int j = i + 1; j &lt; a; j++){
        if(list[i] == list[j]){
          System.out.print(&quot;True&quot;);
          return;
        }
    }
}
System.out.print(&quot;False&quot;); //Print once you&#39;ve seen all the pairs

huangapple
  • 本文由 发表于 2020年10月16日 22:34:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64391228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定