gpt4 book ai didi

java - 如何让数组列表仅保存在文本列表中多次出现的数字的第一次出现?

转载 作者:行者123 更新时间:2023-11-30 03:11:00 24 4
gpt4 key购买 nike

我是java初学者,所以请放轻松。我正在尝试读取一个文件,并仅将文件中出现的第一次出现的重复数字保存到 ArrayList 中。

这是我到目前为止所拥有的:

import java.io.*;
import java.util.Scanner;

public class ListReader
{
File numbers = new File("numbers.txt");
//numbers.txt has numbers {26, 26, 44, 9, 64, 7, 19, 11, 80, 9}
Scanner in = new Scanner(numbers);
ArrayList<Integer> nums = new ArrayList<Integer>();
while(in.hasNextInt())
{
nums.add(in.nextInt());
}
int j = nums.size() - 2;
for(int i = nums.size() - 1; i >= 0; i--)
{
if(nums.get(i) == nums.get(j))
{
nums.remove(nums.get(i)));
j--;
}
else
{
j--;
}
}
System.out.println(nums);
}

每次运行代码时,都会出现索引越界错误,我不知道如何避免。如果越界错误被纠正,是否能成功摆脱多余的26和9?

最佳答案

使用 set 是更简单的方法,但是,如果需要使用列表,请尝试以下操作:

public class ListReader {
//numbers.txt has numbers {26, 26, 44, 9, 64, 7, 19, 11, 80, 9}
ArrayList<Integer> nums = new ArrayList<>();
//I will manually put items into list, just to evade creating a file
//You keep doing your thing :)
void addItems() {
nums.add(26);
nums.add(26);
nums.add(44);
nums.add(9);
nums.add(64);
nums.add(7);
nums.add(19);
nums.add(11);
nums.add(80);
nums.add(9);
}
void removeExtraItems() {
//Creating a list with extraItems that will be removed further
ArrayList<Integer> extraItems = new ArrayList<>();
//Whenever a copy is found from num arrayList - this list gets that copy
ArrayList<Integer> numsCopy = new ArrayList<>();
for (int i = 0; i < nums.size(); i++) {
if(numsCopy.contains(nums.get(i))) {
extraItems.add(nums.get(i));
}
else{numsCopy.add(nums.get(i));
}
}
//for each extraItem, you check the num list backwards - if it finds it , it removes it and break;
//if you go nums.remove(extraItems.get(i)
//it will remove the first occurence
//i guess that you dont want that
for (int i = 0; i < extraItems.size(); i++) {
for (int j = nums.size()-1; j >= 0; j--) {
if(nums.get(j).equals(extraItems.get(i))){
nums.remove(extraItems.get(i));
break;
}
}
}
}
//prints list
void printList() {
for (int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
}
public static void main(String[] args) {
ListReader lr = new ListReader();
lr.addItems();
lr.removeExtraItems();
lr.printList();
}

}

关于java - 如何让数组列表仅保存在文本列表中多次出现的数字的第一次出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33643428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com