有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java逐个扫描元素并进行比较

我得为编程课做些家庭作业。任务是将文本文档作为短程序的输入,删除所有重复的数字,并打印出这些单一的数字。当有两个数字紧随其后时,这种方法就可以了,但当有三个或更多数字紧随其后时,我的程序就会将它们视为“新”数字,从而打印出错误的答案

我已经试过两个扫描仪读取同一个文件,但似乎你不能用不同的扫描仪扫描一个文件两次。 我通常用java来完成这个任务。util。ArrayList,但我们不允许使用它,因为我们的讲座中还没有它。 我可以扩展它,以便能够比较三个数字,但这会使程序太复杂。看来必须有更简单的方法

    Scanner scanner1 = new Scanner(System.in);
    boolean hasPrinted = false;

    while(scanner1.hasNext()){

        int x = scanner1.nextInt();
        if(scanner1.hasNext()){
            int y = scanner1.nextInt();
            if(x != y){
                System.out.println(x);
                System.out.println(y);
                hasPrinted = true;
            }
        }
        if(!hasPrinted) System.out.println(x);
        hasPrinted = false; 
    }

输入是:java RemovedUpplicates<;输入txt

当文本文档类似于1 8 3 3 5 4 4 4 9时,输出应该是1 8 3 5 4 9。我得到的输出是1 8 3 5 4 4 9

非常感谢


共 (1) 个答案

  1. # 1 楼答案

    尝试使用ArrayList:

    ArrayList<Integer> alreadyPrinted = new ArrayList<>();
    while(scanner.hasNext()){
        int number = scanner.nextInt();
        if (!alreadyPrinted.contains(number)){
             System.out.print(number);
             alreadyPrinted.add(number);
        }
    }