我有 3 個陣列,oddList、negativeList 和 evenList,它們從 masterArray 中獲取數字并相應地對它們進行排序。當我列印 3 個陣列時,如果陣列中的某些索引未填充,它會自動填充 0.0 我需要弄清楚如何擺脫這些零并僅使用陣列的邏輯大小。
public static void negoddeven(double masterArray[]){
int z;
int size = 0;
int sum = 0;
double[] negativeList = new double[10], oddList = new double[10], evenList = new double[10];
for(z = 0; z < masterArray.length; z ){
for(int i = 0; i < size; i ){
if(masterArray[z]%2 != 0){
sum = oddList[z];
if(size < oddList.length){
oddList[z] = masterArray[z];
size ;
}}
else if(masterArray[z] < 0){
if(size < negativeList.length){
negativeList[size] = masterArray[z];
size ;
}}
else if(masterArray[z]%2 == 0){
if(size < negativeList.length){
evenList[size] = masterArray[z];
size ;
}}
}
}
System.out.print("\nThe numbers in the odd list are: " Arrays.toString(oddList));
System.out.print("\nThe numbers in the negative list are: " Arrays.toString(negativeList));
System.out.print("\nThe numbers in the even list are: " Arrays.toString(evenList) "\n");
}
uj5u.com熱心網友回復:
使用動態List而不是固定大小的陣列來收集masterArray.
此外,負值應與奇偶校驗分開計算。
public static void negOddEven(double ... masterArray) {
int sum = 0;
List<Double>
negativeList = new ArrayList<>(),
oddList = new ArrayList<>(),
evenList = new ArrayList<>();
for (int i = 0; i < masterArray.length; i ) {
double z = masterArray[i];
if (z < 0) {
negativeList.add(z);
}
if (z % 2 == 0) {
evenList.add(z);
} else {
oddList.add(z);
sum = z;
}
}
System.out.println("The numbers in the odd list are: " oddList "; sum = " sum);
System.out.println("The numbers in the negative list are: " negativeList);
System.out.println("The numbers in the even list are: " evenList "\n");
}
測驗:
negOddEven(1, 2, 3, 0, 4.5, -2, -0.0, -12.2);
輸出:
The numbers in the odd list are: [1.0, 3.0, 4.5, -12.2]; sum = -4
The numbers in the negative list are: [-2.0, -12.2]
The numbers in the even list are: [2.0, 0.0, -2.0, -0.0]
如果由于某些限制而不允許使用串列,而只能使用陣列,則需要為所有陣列的實際長度引入單獨的計數器。使用以下方法切斷陣列中未使用的單元格也很有意義Arrays.copyOf:
public static void negOddEven(double ... masterArray) {
int sum = 0;
double[]
negList = new double[10],
oddList = new double[10],
evenList = new double[10];
int negSz = 0, oddSz = 0, evenSz = 0;
for(int i = 0; i < masterArray.length; i ) {
double z = masterArray[i];
if (z < 0) {
if (negSz < negList.length) {
negList[negSz ] = z;
}
}
if (z % 2 == 0) {
if (evenSz < evenList.length) {
evenList[evenSz ] = z;
}
} else if (oddSz < oddList.length) {
oddList[oddSz ] = z;
sum = z;
}
}
if (negSz < 10) negList = Arrays.copyOf(negList, negSz);
if (oddSz < 10) oddList = Arrays.copyOf(oddList, oddSz);
if (evenSz < 10) evenList = Arrays.copyOf(evenList, evenSz);
System.out.println("The numbers in the odd list are: " Arrays.toString(oddList) "; sum = " sum);
System.out.println("The numbers in the negative list are: " Arrays.toString(negList));
System.out.println("The numbers in the even list are: " Arrays.toString(evenList) "\n");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/345778.html
下一篇:SpringMVC找不到映射
