英文:
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 < 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;
}
}
}
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 < a; i++){
for(int j = i + 1; j < a; j++){
if(list[i] == list[j]){
System.out.print("True");
return;
}
}
}
System.out.print("False"); //Print once you've seen all the pairs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论