【问题标题】:How to find size of ArrayList from separate class in Java?如何从 Java 中的单独类中查找 ArrayList 的大小?
【发布时间】:2011-04-14 19:59:31
【问题描述】:

我正在为家庭作业创建一个非常简单的电话目录,但我卡住了。我尝试过查看类似的线程,虽然这些线程很有用,但它们并没有回答我的问题。我有一个类名 Directory,它有一个从另一个名为 Person 的类编译的 ArrayList。 Person 类收集有关联系人的信息:所有联系人的名字和姓氏、电话号码和电子邮件地址。我正在尝试从另一个类中读取 ArrayList 大小:_MainMenu,这样如果我想添加另一个联系人,方法 addNewPerson 可以是动态的。我将包含 MainMenu 和 Directory 的代码。基本上,我试图避免必须手动为 Person 类创建一个新对象,因为我不知道用户将拥有多少联系人。我希望这是有道理的......对不起,如果没有。毫无疑问,我会尽力澄清问题。

import java.util.Scanner;

public class _MainMenu {
public static Scanner input = new Scanner(System.in);
public static int choice;
public static String firstName = new String();
public static String lastName = "";
public static String phoneNumbers;
public static String emailAddresses;
public static Person pI = new Person ();

public static void main(String[] args) throws Exception
{
    Directory d1 = new Directory("myDir.txt");
    do
    {
    printMenu();
    selectSubMenu();
    if(choice == 1)
    {
        for(int i = 0; i < d1.getSize(); i++)
        d1.addNewPerson(pI);
    }
    }while(choice != 3);
    d1.writeToFile("myDir.txt");
}

public static void printMenu()
{
    System.out.printf("%s\n%s\n%s\n%s\n",
            "Select The Number Of Your Choice: ",
            "1 - Add New Contact",
            "2 - Search (Display/Edit/Remove)",
            "3 - Exit");
}

public static void selectSubMenu()
{
    choice = input.nextInt();
    switch(choice)
    {
        case 1:
            addNewContact();
            break;
        case 2:
//              search();
            break;
        case 3:
            break;
        default:
            System.out.println("Invalid selection. Please try again.");
    }

}

public static void addNewContact()
{
    System.out.println("Please enter the first name: ");
    firstName = input.next();
    System.out.println("Please enter the last name: ");
    lastName = input.next();
    System.out.println("Please enter up to three phone numbers: ");
    phoneNumbers += input.next();
    System.out.println("Please enter up to three email addresses: ");
    emailAddresses += input.next();

}

}

这是目录类的代码:

import java.util.ArrayList;
import java.util.Formatter;
import java.io.File;
import java.util.Scanner;

public class Directory {

private ArrayList <Person> directory = new ArrayList <Person>();

public Directory(String name) throws Exception
{
    File f = new File(name);
    Scanner input;
    if(f.exists())
    {
        input = new Scanner (f);
        while(input.hasNext())
        {
            Person p = new Person();
            p.setFname(input.next());
            p.setLname(input.next());
            int pNumber = input.nextInt();
            for (int i=0; i< pNumber; i++)
                p.setPhone(input.next());
            int eNumber = input.nextInt();
            for (int i=0; i< eNumber; i++)
                p.setemail(input.next());
            directory.add(p);
        }
        input.close();
    }
    else
        f.createNewFile();
}
public Person find(String fName, String lName)
{
    for(int i=0; i<directory.size(); i++)
    {
        if (directory.get(i).getLname().equals(lName) && directory.get(i).getFname().equals(fName))
            return directory.get(i);
    }
    return null;
}

public void addNewPerson(Person p)
{
    directory.add(p);
}
public void writeToFile(String name) throws Exception
{
    Formatter inFile = new Formatter(name);
    for( int i =0; i< directory.size(); i++){
        inFile.format("%s %s %d ", directory.get(i).getFname(),directory.get(i).getLname(),directory.get(i).pNum);
        for(int j=0; j<directory.get(i).pNum; j++)
            inFile.format("%s ",directory.get(i).getPhones()[j]);
        inFile.format("%d ", directory.get(i).eNum);
        for(int j=0; j<directory.get(i).eNum; j++)
            inFile.format("%s ",directory.get(i).getemails()[j]);
    }
    inFile.close();
}
}

我知道 if(choice == 1) 语句中 MainMenu 中的代码不起作用,但我想不出该怎么做。我想让 Person pI 成为动态变量,这样如果用户想添加另一个联系人,那么他选择“添加联系人”,程序将在目录 ArrayList 中已经有多少联系人,然后添加“1”将该新变量输入到“d1.addNewPerson(pI)”中,使其工作如下:“d1.addNewPerson(d1.size() + 1)”...我不知道这是否有意义.无论如何,如果有人能理解它并知道如何处理代码,我将不胜感激。谢谢。

【问题讨论】:

    标签: java arraylist


    【解决方案1】:

    您必须为每个条目创建一个新的 Person 对象。

    Person p = new Person();
    p.firstname = ... 
    p.lastname = ..
    
    d1.addNewPerson(p);
    

    要获取 ArrayList 的大小,您可以尝试d1.directory.size(),因为 director 是一个公共字段。但如果可能的话,你应该把它设为私有并向目录添加一个方法

    public int getSize()
    {
        return directory.size();
    }
    

    编辑:

    你可以把你的代码修改成这样的

    if(choice == 1)
    {
            Person p = new Person();
            p.firstname = ... 
            p.lastname = ..
    
    
            d1.addNewPerson(pI);
     }
    

    【讨论】:

    • 好的。但我不知道需要多少 Person 对象,因为这取决于用户。
    • @Michael 您不必事先知道它,因为您使用的是 ArrayList。您可以继续向其中添加 Person 对象,而 ArrayList 负责调整大小。查看我的编辑
    • 感谢您进行最终编辑。这有帮助,正是我所需要的。我不明白 ArrayList 可以处理的所有问题。
    猜你喜欢
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2015-05-07
    • 2012-05-02
    • 2013-05-07
    • 1970-01-01
    相关资源
    最近更新 更多