Java 在我的代码中,我需要什么来检查数组中的元素是否与前面的元素相同
我需要制作一个程序来比较数组中的元素是否有相同的值,如果数组中有相同的元素,它会打印“是”,否则会打印“否”Java 在我的代码中,我需要什么来检查数组中的元素是否与前面的元素相同,java,arrays,Java,Arrays,我需要制作一个程序来比较数组中的元素是否有相同的值,如果数组中有相同的元素,它会打印“是”,否则会打印“否” 导入java.io.File; 导入java.io.FileNotFoundException; 导入java.util.Scanner; 公共类DistinctNumbers{ 公共静态void main(字符串[]args)引发FileNotFoundException{ 扫描仪=新扫描仪(新文件(“number.in”); int sizeN=scanner.nextInt();
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.util.Scanner;
公共类DistinctNumbers{
公共静态void main(字符串[]args)引发FileNotFoundException{
扫描仪=新扫描仪(新文件(“number.in”);
int sizeN=scanner.nextInt();
int[]arrayA=新int[sizeN];
for(int i=0;i
[编辑](见下文)
你是说像这样的事吗
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");
}
}
}
}
publicstaticvoidmain(字符串[]args)抛出FileNotFoundException{
扫描仪=新扫描仪(新文件(“number.in”);
int sizeN=scanner.nextInt();
int[]arrayA=新int[sizeN];
对于(int i=0;i
你能给我们一个预期的输入和预期的输出吗?
您想要一个简单的是或否作为输出,还是一系列的是或否作为输出
[编辑]
如果您试图检查数组中是否有2个或更多具有相同值的数字,这可能对您有用(但不是最佳值):
publicstaticvoidmain(字符串[]args)抛出FileNotFoundException{
扫描仪=新扫描仪(新文件(“number.in”);
int sizeN=scanner.nextInt();
int[]arrayA=新int[sizeN];
布尔值=false;
对于(int i=0;!已找到&&i
我想你想做:
if (arrayA[i] == arrayA[j]) {
System.out.println("Yes");
} else {
System.out.println("No");
}
如果数组中的任何元素相同,则为“是”您应该说明问题所在。只需看一眼,您似乎只是在检查元素arrayA[0]是否已经存在,而不是arrayA[1]==arrayA[2]等。编辑:并且您在j for循环中增加了i这段代码看起来确实有缺陷这回答了您的问题吗@我是否需要添加“else if”?当我尝试运行输出代码时,它会打印“Yes”“No”“No”,例如,当数组元素为{1,2,1,3}时,它只会打印“Yes”。如果没有某些值的元素,比如{5,4,1,2,3}。将打印“否”。
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");
}
}
if (arrayA[i] == arrayA[j]) {
System.out.println("Yes");
} else {
System.out.println("No");
}