【问题标题】:How to add multiple variables as a single value in an arraylist?如何将多个变量作为单个值添加到数组列表中?
【发布时间】:2016-12-24 16:47:58
【问题描述】:

今天我需要一些帮助,将 4 个用户定义的字符串、2 个 int 和 4 个 double 变量作为一个索引添加到数组列表中。

例如:(我会为您减少一些变量,并记住 sc 是我的扫描仪对象,测试结果超出 100)

System.out.print("enter your name")
String name = sc.next();
System.out.print("enter your test results")
double results = sc.nextDouble();
System.out.print("enter your mobile number")
int mobile_num = sc.nextInt();  //I may change this to a string

现在,我想从这里捕获这些输入并将它们存储在数组中的数字 1 或用户名下。我也想知道如何通过上面提到的代码使用这个相同的数组来存储来自用户的无限输入。

提前致谢!

【问题讨论】:

    标签: java arraylist


    【解决方案1】:

    创建你自己的类UserInput,它保留10个字段,然后用这种类型概括List

    List<UserInput> list = new ArrayList<>();
    list.add(new UserInput(name, results, mobile_num, ...));
    

    如果你想把一个用户的名字和他对应的输入关联起来,你最好考虑一个Map&lt;String, UserInput&gt;

    Map<String, UserInput> map = new HashMap<>();
    map.put(name, new UserInput(results, mobile_num, ...));
    

    【讨论】:

    • 但是如果我为 UserInput 创建一个公共类,我会收到很多错误
    • @BzeQ,先阅读the tutorial
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 2020-12-10
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多