java 如何在代码内部初始化具有可变长度的浮点数组,但具有相同的开始和结束值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38555262/
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 do I initialize a float array, with variable lengths, inside the code, but with the same start and end values?
提问by Luke Goss
PdfPTable table = new PdfPTable(new float[]{4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2});
This is the initializer I currently use.
这是我目前使用的初始化程序。
It's for a scorecard in Disc Golf, using integers to tell how wide each cell should be, but some courses have different numbers of holes (9, 18 ,24, etc). The array MUST start with a 4, for the players name, and MUST end with a 2, for totals. All cell values for individual holes are set at 1. I want to save code by using a variable in the initializer. Any help would be awesome!!
它用于 Disc Golf 中的记分卡,使用整数来表示每个单元格的宽度,但有些球场的洞数不同(9、18、24 等)。数组必须以 4 开头,代表球员姓名,必须以 2 结尾,代表总数。各个孔的所有单元格值都设置为 1。我想通过在初始化程序中使用变量来保存代码。任何帮助都是极好的!!
回答by Durandal
You do know that you can create arrays of variable size by using a variable as the array length?
您知道可以通过使用变量作为数组长度来创建可变大小的数组吗?
public float[] newFloatArray(int size) {
float[] array = new float[size];
return array;
}
Filling the array can be done with a loop or using the JRE supplied Arrays class helper methods. You will need to handle the first and last index in the array separately:
可以使用循环或使用 JRE 提供的 Arrays 类辅助方法来填充数组。您需要分别处理数组中的第一个和最后一个索引:
public float[] newGolfArray(int size) {
float[] array = new float[size];
Arrays.fill(array, 1F);
array[0] = 4F;
array[size - 1] = 2F;
return array;
}