我正在使用 ArrayList 来记录几个新创建的 Person 对象。我的问题是,当我调用构造函数来实例化 Person 对象时,Java 将无法识别该方法(构造函数)。我收到一条错误消息:the method Person(String, int) is not defined for the Type DemoList
为什么 Java 没有意识到我正在尝试在这里创建另一个对象?
import java.util.ArrayList;
import java.util.Scanner;
public class DemoList {
//input from keyboard
static Scanner reader = new Scanner(System.in);
static ArrayList<Person> array = new ArrayList<Person>();
public static void main(String[] args)
{
System.out.println("To quit, press 0, to continue, press 1 \n");
int in = 1;
while(in !=0)
{
System.out.println("Please enter a name: ");
String name = reader.nextLine();
System.out.println("Please enter a telephone number");
int number = reader.nextInt();
Person newPerson = Person(name, number);
array.add(newPerson);
System.out.println("Press 1 to continue or 0 to quit");
in = reader.nextInt();
}
//The user typed 0
System.out.println("Who would you like to delete? ");
String name = reader.nextLine();
for(int i = 0; i < array.size(); i++)
{
Person searchPerson = array.get(i);
if(searchPerson.name == name)
{
array.remove(i);
break;
}
}
PrintArray();
}
public static void PrintArray()
{
System.out.println("-------------------------------");
//scroll through each item in array and put it in variable i
for(Person i : array)
{
System.out.println(i);
}
}
}
class Person
{
protected String name;
protected int number;
public Person(String name, int number)
{
System.out.println("Person object created! \n");
this.name = name;
this.number = number;
}
}
最佳答案
要创建 Person
对象,您需要使用关键字 new
告诉编译器创建一个 Person
对象(这将间接导致正在使用的构造函数),而不是像方法一样尝试直接调用构造函数
Person newPerson = new Person(name, number);
关于java - 尝试创建新对象时,未为类型定义方法...,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35675039/