我需要编写一个程序来比较数组中的元素是否具有相同的值,如果数组中的元素具有相同的值,则打印“是”,否则显示“否”。
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");
}
}
}
}
}
答案 0 :(得分:0)
[已编辑] (请参见下文)
你的意思是这样吗?
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");
}
}
答案 1 :(得分:0)
我想你想做:
if (arrayA[i] == arrayA[j]) {
System.out.println("Yes");
} else {
System.out.println("No");
}
如果数组中的任何元素相同,则为“是”