当我尝试将某些内容放在Friends f = new Friends(friendsName, friendsAge);的()括号中时,出现错误:



但是当我删除参数时,我的 friend 列表仅显示“空0”。即使我有String friendsName = input.next();也未设置值吗?

另外,当我尝试删除 friend 时,它什么也没做。在源代码中,它确实会发出警告,



我对这意味着什么感到困惑?

import java.util.ArrayList;
import java.util.Scanner;

public class Friends
{
    public static void main( String[] args )
    {
        int menu;
        int choice;
        choice = 0;

        Scanner input = new Scanner(System.in);
        ArrayList< Friends > friendsList = new ArrayList<  >();

        System.out.println(" 1. Add a Friend ");
        System.out.println(" 2. Remove a Friend ");
        System.out.println(" 3. Display All Friends ");
        System.out.println(" 4. Exit ");
        menu = input.nextInt();

        while(menu != 4)
        {

            switch(menu)
            {

            case 1:

                while(choice != 2)
                {
                    System.out.println("Enter Friend's Name: ");
                    String friendsName = input.next();
                    System.out.println("Enter Friend's Age: ");
                    int friendsAge = input.nextInt();
                    Friends f = new Friends(friendsName, friendsAge);
                    friendsList.add(f);
                    System.out.println("Enter another? 1: Yes, 2: No");
                    choice = input.nextInt();
                } break;

            case 2:

                System.out.println("Enter Friend's Name to Remove: ");
                friendsList.remove(input.next());
                break;

            case 3:

                for(int i = 0; i < friendsList.size(); i++)
                {
                    System.out.println(friendsList.get(i).name + " " + friendsList.get(i).age);
                } break;
        }

        System.out.println(" 1. Add a Friend ");
        System.out.println(" 2. Remove a Friend ");
        System.out.println(" 3. Display All Friends ");
        System.out.println(" 4. Exit ");
        menu = input.nextInt();

    }

    System.out.println("Thank you and goodbye!");

}

    public String name;
    public int age;

    public void setName( String friendsName )
    {
        name = friendsName;
    }
    public void setAge( int friendsAge )
    {
        age = friendsAge;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
}

最佳答案

您尝试像这样实例化Friends类的对象:

Friends f = new Friends(friendsName, friendsAge);

该类没有带参数的构造函数。您应该添加构造函数,或者使用存在的构造函数创建对象,然后使用set方法。例如,代替上面的内容:
Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);

关于java - “Actual or formal argument lists differs in length”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17749409/

10-10 19:16