Java如何从一个数组中打印两个不同的值

时间:2013-05-09 13:36:26

标签: java arrays sorting

我正在努力从一组存储的计算机模型中打印两个不同的值。目前我的程序从索引打印第一台计算机,但我无法得到如何打印一个特定的模型。 这是我的Main类的片段

ComputerList list = new ComputerList();
Coputer item;
String model;
switch (option) 
{
    case 'M':
       model = Console.askString("Enter model?: ");
   item = list.findModel(model);
if (item == null)
   System.out.println("Cannot find " + model);
else
   item.print("Computer details..." + model);

...这是我的ComputerList类

ArrayList<Laptop> laptops;
private ArrayList<String> models;   
    public SerialList()
{
laptops = new ArrayList<Laptop>();
models = new ArrayList<String>();
}

public void add(Computer anComputer)
{
laptops.add(anComputer);
models.add(anComputer.getModel());
}

public void print()
{

    int nItems = computer.size();
    for (int i=0; i<nItems; i++)
    {
        System.out.println(computers.get(i));

}

public Computer findModel(String aModel)
{
    int index = models.indexOf(aModel);
    if (index == -1)
        return null;
    else
        return computers.get(index);
}

}

我真的很难解决这个问题几天,但大多数教程都基于数字,数值等。 我将非常感谢对此事的任何帮助。 此致

2 个答案:

答案 0 :(得分:1)

您需要通过ComputerList进行列表迭代。

ComputerList list = new ComputerList();

for (ComputerList currentComputer: list) {
     currentComputer.print();
}

记住格式。此外,我会使用HashMap或不同的集合来实现一对一的字符串 - &gt;笔记本电脑通信。

答案 1 :(得分:1)

当您打印对象时,您将获得标识符@ 222222等...

您必须打印属性。 System.out.println(computer.getName + computer.getID);