当我尝试将某些东西放在()括号中Friends f = new Friends(friendsName, friendsAge);
它提出了错误:
班级朋友中的构造者朋友不能应用于给定类型。必需:没有争论。找到:字符串,int。原因:实际论证列表的长度有所不同。
但是,当我提出论点时,我的朋友列表仅显示" null 0"。即使我有String friendsName = input.next();
?
另外,当我尝试删除朋友时,它无能为力。在源代码中,它确实提出了警告,
可疑呼叫to util.java.collection.remove:给定的对象不能包含给定的字符串实例(预期的朋友)。
我对这一切的含义感到困惑?
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-Methods。例如,而不是上述:
Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);