我需要编写一个程序来比较数组中的元素是否具有相同的值,如果数组中存在相同的元素,则打印"is",否则打印“否”。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class DistinctNumbers {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.in"));
int sizeN = scanner.nextInt();
int[] arrayA = new int[sizeN];
for (int i = 0; i < arrayA.length; i++) {
for (int j = i + 1; j < arrayA.length; j++) {
arrayA[j] = scanner.nextInt();
if (arrayA[0] == arrayA[i++]) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
}
最佳答案
[已编辑] (见下文)
你的意思是这样吗?
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.in"));
int sizeN = scanner.nextInt();
int[] arrayA = new int[sizeN];
for (int i = 0; i < sizeN; i++) {
arrayA[i] = scanner.nextInt();
for (int j = 0; j < i; j++) {
if (arrayA[i] == arrayA[j]) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
您能给我们一个预期的输入和预期的输出吗? 您想要一个简单的是或否作为输出,还是一系列是或否作为输出?
[编辑]
如果您尝试检查数组中是否有 2 个或更多具有相同值的数字,这可能适合您(但这不是最佳选择):
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.in"));
int sizeN = scanner.nextInt();
int[] arrayA = new int[sizeN];
boolean found = false;
for (int i = 0; !found && i < sizeN; i++) {
arrayA[i] = scanner.nextInt();
for (int j = 0; !found && j < i; j++) {
if (arrayA[i] == arrayA[j]) {
found = true;
}
}
}
if (found) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
关于java - 我的代码中需要什么来检查数组中的元素是否与前一个元素相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60203629/