Java 如何初始化整数列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23280652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize a list of integers
提问by mrsW
I need to create a list of available television channels (identified by integers). I am thinking that I would begin by creating int [] list = 5,9,12,19,64. Here is the code:
我需要创建一个可用电视频道列表(由整数标识)。我想我会从创建 int [] list = 5,9,12,19,64 开始。这是代码:
public NotVeryGoodTV(int[] channels) {
int [] list =5,9,12,19,64;
but I am getting a syntax error stating that a { is needed after "=". I would like to have a list of tv channels that would be available to the user once they turned on their television.
但我收到一个语法错误,指出在“=”之后需要一个 {。我想要一个电视频道列表,用户打开电视后可以使用这些频道。
回答by Anubian Noob
Replace:
代替:
int [] list =5,9,12,19,64;
With:
和:
int[] list = { 5,9,12,19,64 };
The brackets tell Java that you are declaring a list.
括号告诉 Java 您正在声明一个列表。
However the numbers are not random; they are the ssame every time.
然而,这些数字不是随机的;他们每次都是一样的。
回答by WoDoSc
This is syntactically correct (instead of your array declaration):
这在语法上是正确的(而不是您的数组声明):
int[] list = {5, 9, 12, 19, 64};
But it is not random, if you want to create an array with random integers:
但它不是随机的,如果你想用随机整数创建一个数组:
Random randGen = new Random(); //random generator: import java.util.Random;
int maxChanNumber=64; //upper bound of channel numbers (inclusive)
int minChanNumber=1; //lower bound of channel numbers (inclusive)
int amountOfChans=5; //number of channels
int[] list = new int[amountOfChans]; //create an array of the right size
for (int k=0;k<amountOfChans;k++) //populate array
list[k]=minChanNumber+randGen.nextInt(maxChanNumber-minChanNumber+1);
Actually this codes does NOT check if you generate a different channel number (integer) for every item of the array: it is possible that in the array you will find two or more times the same number, but it is not difficult to adapt the code to avoid this, anyway the direction to take to have really random channel numbers is this one.
实际上,此代码不会检查您是否为数组的每个项目生成了不同的通道编号(整数):您可能会在数组中找到两倍或更多倍的相同数字,但修改代码并不困难为了避免这种情况,无论如何,拥有真正随机频道号的方向就是这个。
回答by Jake
Yep, you need to encase the list in curly braces like this:
是的,您需要将列表括在花括号中,如下所示:
int [] list = {5, 9, 12, 19, 64};
回答by Curlip
replace line 2:
替换第 2 行:
int [] list =5,9,12,19,64;
with this code:
使用此代码:
int[] list = {5,9,12,19,64};