java - 我的代码中需要什么来检查数组中的元素是否与前一个元素相同

标签 java arrays

我需要编写一个程序来比较数组中的元素是否具有相同的值,如果数组中存在相同的元素,则打印"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/

相关文章:

C++ 错误无法为 char g[] 的数组指定显式初始值设定项

javascript - 使用 javascript 检查数组中删除索引的条件

java - 迭代器,当 hasNext() 等于 false 时做一些事情

java - 当我从 addMouseListener 关闭我的框架时,它说这是不兼容的类型,那么我可以用什么来改变它呢?

java - android java上下文解释

python - 修剪/去除 numpy 数组的零点

java - 检测 Android Activity 子类中的连接变化

java - 闪烁的 JFrame

c - 如何将字符串分配给 char* 指针?

c - 无法确定指针数组的大小