当前位置: 首页 > 知识库问答 >
问题:

将新对象追加到数组列表的开头[重复]

夏侯彬郁
2023-03-14

问题是:“要求用户输入其国家的详细信息,使用输入的值创建一个国家的新对象,并将其附加到数组列表的开头。”

我确实遵循了最基本的规则来防止任何错误,但是当我试图编译时。它复制了一些像日本和美国这样的物体。尝试许多不同的方法来调试和理解问题,但我找不到。

import java.util.*;

public class Country{
    private String name;
    private String continent;
    private int area;
    private double population;

    //Constructor, mutator, accessor method minimized    

    public String toString() {
        return "Name: " + name + ", Continent: " + continent + ", Area: " + area + ", Population: " + population;
    }


    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        ArrayList<Country> ct = new ArrayList<>();

        ct.add(new Country("Nepal", "Asia", 147516, 29.14));
        ct.add(new Country("Japan", "Asia", 377975, 125.8));
        ct.add(new Country("Kazakhstan", "Asia", 2725000, 18.75));
        ct.add(new Country("United States", "North America", 9834000, 329.5));
        ct.add(new Country("Australia", "Oceania", 7692000, 25.69));

        System.out.print("Your country name:");
        String name = sc.nextLine();
        System.out.print("Continent: ");
        String continent = sc.nextLine();
        System.out.print("Area: ");
        int area = sc.nextInt();
        System.out.print("Population: ");
        double population = sc.nextDouble();
        ct.add(0, new Country(name, continent, area, population));

        for(Country country : ct){
        System.out.println(country.toString());
            if(country.getContinent().contains("Asia")){
                System.out.println(country.toString());
            }
            if(country.getPopulation() >= 100 && country.getPopulation() <= 500){
                System.out.println(country);
            }
        }
    }
}

共有1个答案

叶经略
2023-03-14

您可能需要的是:

ct.add(0, new Country("Nepal", "Asia", 147516, 29.14));
ct.add(0, new Country("Japan", "Asia", 377975, 125.8));

 类似资料:
  • 我试图做的是从列“in_reply_to_user_id”(不在图片中,因为df太宽,无法容纳)与给定id具有相同值的行中获取文本,并将文本附加到列表中,然后将其放入新列中。例如,所有tweet中的“in_reply_to_user_id”列等于第一条tweet的“id”的文本都应该放在一个列表中,然后添加到数据框中名为“reples”的新列中。以下是我尝试过的一些事情:

  • 我有一个类来代表一个玩家的手牌。但是,我(在另一个类中)有一个数组列表,我想在其中表示一堆玩家手。问题是我不知道如何在多手牌的数组列表中将一张牌添加到手牌中。我有一个代表卡牌和一副牌的类,效果很好。我只是试图了解如何将对象添加到数组列表中的对象。谢谢!

  • 我有List sample1=lists.newarrayList(BIGINTEGER1,BIGINTEGER2,BIGINTEGER3); 我必须创建一个新的列表sample2,其中还有一个值“bigInteger4”,以及sample1列表: 我怎么能那样做?

  • 问题内容: 假设您有一些AppendObjectOutputStream类(这是一个ObjectOutputStream!),它重写了writeStreamHeader(),如下所示: 现在,假设您打算将多个对象保存到一个文件中。程序每次运行时,一个对象。即使在第一次运行时,您是否也会使用AppendObjectOutputStream()? 问题答案: 您必须首先使用常规ObjectOutput

  • 假设您有一些AppendObjectOutputStream类(这是一个ObjectOutputStream!)将重写writeStreamHeader(),如下所示: 现在,假设您计划将多个对象保存到一个文件中;每次程序运行一个对象。即使在第一次运行时,您也会使用AppendObjectOutputStream()吗?

  • 我正在从HttpServer升级到HttpClientService,作为升级的一部分,我必须将标题从标题切换到HttpHeaders。但是由于某些原因,我的自定义标题不再被追加。我需要更新什么才能添加标题? 该方法返回一个httpHeader,但它是空的。