英文:
How to initialize a list inside a constructor?
问题
我有一个任务,需要在构造类内部初始化一个列表,但我不确定如何为主类中的参数进行赋值。
以下是我目前拥有的代码。
public CoinSorter(String currency, int maxCoinIn, int minCoinIn, List<Integer> coinList) {
this.currency = currency;
this.maxCoinIn = maxCoinIn;
this.minCoinIn = minCoinIn;
coinList = new ArrayList<Integer>();
coinList.add(10);
coinList.add(20);
coinList.add(50);
coinList.add(100);
coinList.add(200);
}
主类代码如下:
CoinSorter cs = new CoinSorter("£", 10000, 0);
任何帮助将不胜感激!
英文:
I have an assignment where I need to initialize a list inside a constructor class, however I am not sure how to put the parameters in for the Main class.
This is the code that I have so far.
public CoinSorter(String currency, int maxCoinIn, int minCoinIn, List<Integer> coinList) {
this.currency = currency;
this.maxCoinIn = maxCoinIn;
this.minCoinIn = minCoinIn;
coinList = new ArrayList<Integer>();
coinList.add(10);
coinList.add(20);
coinList.add(50);
coinList.add(100);
coinList.add(200);}
and the main class code is
CoinSorter cs = new CoinSorter("£", 10000, 0);
Any help would be appreciated!
答案1
得分: 0
public class Main {
public static void main(String[] args) {
CoinSorter cs = new CoinSorter("£", 10000, 0);
}
}
public class CoinSorter {
public String currency;
public int maxCoinIn, minCoinIn;
public List<Integer> coinList = new ArrayList<Integer>();
public CoinSorter(String currency, int maxCoinIn, int minCoinIn) {
this.currency = currency;
this.maxCoinIn = maxCoinIn;
this.minCoinIn = minCoinIn;
this.coinList.addAll(Arrays.asList(10, 20, 50, 100, 200));
}
}
英文:
public class Main {
public static void main(String[] args) {
CoinSorter cs = new CoinSorter("£", 10000, 0);
}
}
public class CoinSorter {
public String currency;
public int maxCoinIn, int minCoinIn;
public List<Integer> coinList = new ArrayList<Integer>();
public CoinSorter(String currency, int maxCoinIn, int minCoinIn) {
this.currency = currency;
this.maxCoinIn = maxCoinIn;
this.minCoinIn = minCoinIn;
this.coinList.addAll(Arrays.asList(10, 20, 50, 100, 200));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论