构造函数和数组列表

时间:2018-12-01 03:29:31

标签: java arrays list constructor

我正在尝试创建一个程序(美国总统)。我想创建一个数组列表(总统编号,总统姓名,开始年份,去年)。

出于某种原因,我的构造函数无法正常工作,我不得不构建另一个方法,但是第二个方法导致StackOverFlowError(这是我第一次认为我是在使用此网站来提问,我认为我是来给定网站名称的正确位置)

这是我的代码:

import copy

    def instantiate_mdl(dim_maxes, base=0):
        """ Instantiate multi-dimensional list, that is a list of list of list ...

        Arguments:
            dim_maxes (list[int]): a list of dimension sizes, for example 
            [2, 4] represents a matrix (represented by lists) of 2 rows and 
            4 columns.     

            base (object): an optional argument indicating the object copies
            of which will reside at the lowest level in the datastructure.
        Returns:
            base (list[base]): a multi-dimensional list of lists structure,
            which is filled with clones of the base parameter.
        """
        for dim_max in reversed(dim_maxes):
            base = [copy.deepcopy(base) for i in range(dim_max)]
        return base

data = instantiate_mdl([3, 5])
data[0][0] = 99999
data[1][1] = 88888
data[2][4] = 77777

for r in data:
    print(r)

>>> # Output
>>> [99999, 0, 0, 0, 0]
>>> [0, 88888, 0, 0, 0]
>>> [0, 0, 0, 0, 77777]

4 个答案:

答案 0 :(得分:4)

您在这里有一种方法:

public Presidents [] PresidentList ()

    {       


        Presidents [] president = new Presidents [45];
        president [0] = Presidents(1, "George Washington", 1789, 1797);
        president [1] = Presidents(2, "John Adams", 1797, 1801);
        president [2] = Presidents(3, "Thomas Jefferson", 1801, 1809);
        president [3] = Presidents(4, "James Madison", 1809, 1817);
        president [4] = Presidents(5, "James Monroe", 1817, 1825);
        //...
        return president;
}

但是每次致电:

president [...] = Presidents(...);

会打电话给

private Presidents Presidents(int i, String string, int j, int k) {

    return Presidents (i, string, j, k);
}

哪个调用具有相同参数的相同方法,该方法将永远递归,从而导致堆栈溢出错误。


没有与该类称为同一个东西并返回某些东西的方法。这是为构造函数保留的。您已经有一个使用适当参数的构造函数,因此只需删除该方法即可:

private Presidents Presidents(int i, String string, int j, int k) {

    return Presidents (i, string, j, k);
}

然后在您的方法中,需要添加new关键字:

president [0] = new Presidents(1, "George Washington", 1789, 1797);
                 ^--- Here

答案 1 :(得分:1)

要在列表中的特定位置进行分配时,需要实例化新的President对象。

这里是您的方法:-

.includes

-此处未实例化类private Presidents Presidents(int i, String string, int j, int k) { //does not Instantiate a new object return Presidents (i, string, j, k); } 的新对象。它调用相同的Presidents方法,然后进行递归调用。

因此,这里您需要使用Presidents关键字实例化您的方法。

new

它指向该类,构造函数将被调用。

答案 2 :(得分:1)

初始化数组时,应该创建Presidents类的新对象,因为该数组应该存储Presidents类型的对象。相反,您仅调用了该类的构造函数。而不是这样做:

if __name__ == "__main__":
    try:
        threads = [threading.Thread(name='daemon', target=daemon)
                   for _ in range(8)]
        for th in threads:
            th.daemon = True
            th.start()

        for th in threads:
            while th.isAlive():
                th.join(1)

    except KeyboardInterrupt:
        print('ctrl-c')

您应该这样做:

[Route("api/[controller]")]
[ApiController]
public class FilesController : Controller
{
    private IFilesService _filesService { get; set; }

    public FilesController(IFilesService filesService)
    {
        _filesService = filesService;
    }

    [HttpPost]
    public async Task<IActionResult> UploadFile(IFormFile file)
    {
        var model = await _filesService.UploadFile(file);
        return Ok();
    }
}

对其余的数组索引也执行此操作。而这种方法:

president [0] = Presidents(1, "George Washington", 1789, 1797);

这是定义方法的错误方法。该方法不应与该类具有相同的名称。只有构造函数应该具有它。另外,如果您希望此方法返回Presidents类的对象,则return语句应如下所示:

president [0] = new Presidents(1, "George Washington", 1789, 1797);

但是该方法没有意义,因为您已经有 PresidentList()方法返回数组。话虽这么说,最好将类内部的变量设为私有并定义getter方法来访问它们。无论如何,我已经对您的代码进行了一些修改,这应该可行:

private Presidents Presidents(int i, String string, int j, int k) {         
    return Presidents (i, string, j, k);
}

主要类别:

return Presidents (i, string, j, k);

我认为您正在尝试按所输入的数字打印所有总裁。如果没有,您可以在main方法中删除for循环。

答案 3 :(得分:0)

解决方案

  • 创建总裁名单的逻辑必须移至主要阶层

原因

  • 逻辑是程序的责任
  • 将职责分配给各个班级至关重要
  • 一个对象可能负责使用构造函数创建自己的单个实例。但不负责使用另一个实例方法创建自己的实例列表。
  • 在您的代码中,您将拥有一个President对象,该对象在字段中没有任何值。该虚拟实例负责创建总统的真实名单。

代码

public class Presidents {   

public int presidentNumber;
public String presidentName;
public int startingYear;
public int endingYear;

public Presidents(int PresidentNumber, String NameOfPresident, int StartingYear, int EndingYear)
{
    this.presidentNumber = PresidentNumber;
    this.presidentName = NameOfPresident;
    this.startingYear = StartingYear;
    this.endingYear = EndingYear;

}
public Presidents() {}
}

import java.util.Scanner;
import java.util.Random;


public class PresidentsQuiz {

public static void main (String [] args)    
{       
    System.out.println("Do you know the 45 presidents of the United States? Enter a number between 1 and 45");

    Scanner kb = new Scanner (System.in);           
    int input =  kb.nextInt();

    while (input < 1 ||  input > 45)        
    {
        System.out.println("Enter a number between 1 and 45");
        input =  kb.nextInt();
    }

    Presidents [] president = new Presidents [45];
    president [0] = new Presidents(1, "George Washington", 1789, 1797);
    president [1] = new Presidents(2, "John Adams", 1797, 1801);
    president [2] = new Presidents(3, "Thomas Jefferson", 1801, 1809);
    president [3] = new Presidents(4, "James Madison", 1809, 1817);
    president [4] = new Presidents(5, "James Monroe", 1817, 1825);
    president [5] = new Presidents(6, "John Quincy Adams", 1825, 1829);
    president [6] = new Presidents(7, "Andrew Jackson", 1829, 1837);
    president [7] = new Presidents(8, "Martin Van Buren", 1837, 1841);
    president [8] = new Presidents(9, "William Henry Harrison", 1841, 1841);
    president [9] = new Presidents(10, "John Tyler", 1841, 1845);
    president [10] = new Presidents(11, "James K. Polk", 1845, 1849);
    president [11] = new Presidents(12, "Zachary Taylor", 1849, 1850);
    president [12] = new Presidents(13, "Millard Fillmore", 1850, 1853);
    president [13] = new Presidents(14, "Franklin Pierce", 1853, 1857);
    president [14] = new Presidents(15, "James Buchanan", 1857, 1861);
    president [15] = new Presidents(16, "Abraham Lincoln", 1861, 1865);
    president [16] = new Presidents(17, "Andrew Johnson", 1865, 1869);
    president [17] = new Presidents(18, "Ulysses S. Grant", 1869, 1877);
    president [18] = new Presidents(19, "Rutherford B. Hayes", 1877, 1881);
    president [19] = new Presidents(20, "James A. Garfield", 1881, 1881);
    president [20] = new Presidents(21, "Chester A. Arthur", 1881, 1885);
    president [21] = new Presidents(22, "Grover Cleveland", 1885, 1889);
    president [22] = new Presidents(23, "Benjamin Harrison", 1889, 1893);
    president [23] = new Presidents(24, "Grover Cleveland", 1893, 1897);
    president [24] = new Presidents(25, "William McKinley", 1897, 1901);
    president [25] = new Presidents(26, "Theodore Roosevelt", 1901, 1909);
    president [26] = new Presidents(27, "William Howard Taft", 1909, 1913);
    president [27] = new Presidents(28, "Woodrow Wilson", 1913, 1921);
    president [28] = new Presidents(29, "Warren G. Harding", 1921, 1923);
    president [29] = new Presidents(30, "Calvin Coolidge", 1923, 1929);
    president [30] = new Presidents(31, "Herbert Hoover", 1929, 1933);
    president [31] = new Presidents(32, "Franklin D. Roosevelt", 1933, 1945);
    president [32] = new Presidents(33, "Harry S. Truman", 1945, 1953);
    president [33] = new Presidents(34, "Dwight D. Eisenhower", 1953, 1961);
    president [34] = new Presidents(35, "John F. Kennedy", 1961, 1963);
    president [35] = new Presidents(36, "Lyndon B. Johnson", 1963, 1969);
    president [36] = new Presidents(37, "Richard Nixon", 1969, 1974);
    president [37] = new Presidents(38, "Gerald Ford", 1974, 1977);
    president [38] = new Presidents(39, "Jimmy Carter", 1977, 1981);
    president [39] = new Presidents(40, "Ronald Reagan", 1981, 1989);
    president [40] = new Presidents(41, "George H. W. Bush", 1989, 1993);
    president [41] = new Presidents(42, "Bill Clinton", 1993, 2001);
    president [42] = new Presidents(43, "George W. Bush", 2001, 2009);
    president [43] = new Presidents(44, "Barack Obama", 2009, 2017);
    president [44] = new Presidents(45, "Donald Trump", 2017, 2018);

    System.out.println(presidentList [0]);
    kb.close();

}

}