方法...没有为类型whem尝试创建新对象定义

时间:2016-02-27 20:25:49

标签: java

我使用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;

    }
}

2 个答案:

答案 0 :(得分:2)

要创建Person对象,您需要使用关键字new来告诉编译器创建一个Person对象(这将间接导致使用构造函数),而不是尝试直接调用构造函数,如方法

Person newPerson = new Person(name, number);

答案 1 :(得分:0)

行号 22 中缺少新关键字,同时实例化Person类:

Person newPerson = new Person(name, number);