I have an array of integers.
我有一个整数数组。
18 9 22 34 11 8 15 13 2 55
and a separate integer. 12
How can I remove all the integer element that is less than 12
so the resulting array will be
和一个单独的整数。 12如何删除小于12的所有整数元素,以便生成数组
18 22 34 15 13 55
Thank you in advance.
先感谢您。
2 个解决方案
#1
2
int count = 0; //initialize count
for(int i = 0; i < arrayname.length; i++){
if(arrayname[i] > 12){
count++; //iterate original array, getting number of integers greater than 12
}
}
int[] newarray = [count]; //initialize new array to this number
count = 0; //reinitialize count to begin at first element in new array
for(int i = 0; i < arrayname.length; i++){
if(arrayname[i] > 12){
newarray[count] = arrayname[i]; //set each element >12 in original to next element in new array
count++; //move through new array
}
}
Hope this helps :-)
希望这可以帮助 :-)
#2
2
Since this is clear homework, I show my disagreement and down vote with my answer
由于这是明确的家庭作业,我用我的答案表明我的不同意见和投票
In Java 8
:
在Java 8中:
Code:
List<Integer> list1 = Arrays.asList(18, 9, 22 ,34 ,11 ,8 ,15 ,13, 2 ,55);
list1.stream()
.filter( i -> i > 12)
.forEach( i -> System.out.print(i + " "));
Output: 18 22 34 15 13 55
产出:18 22 34 15 13 55
#1
2
int count = 0; //initialize count
for(int i = 0; i < arrayname.length; i++){
if(arrayname[i] > 12){
count++; //iterate original array, getting number of integers greater than 12
}
}
int[] newarray = [count]; //initialize new array to this number
count = 0; //reinitialize count to begin at first element in new array
for(int i = 0; i < arrayname.length; i++){
if(arrayname[i] > 12){
newarray[count] = arrayname[i]; //set each element >12 in original to next element in new array
count++; //move through new array
}
}
Hope this helps :-)
希望这可以帮助 :-)
#2
2
Since this is clear homework, I show my disagreement and down vote with my answer
由于这是明确的家庭作业,我用我的答案表明我的不同意见和投票
In Java 8
:
在Java 8中:
Code:
List<Integer> list1 = Arrays.asList(18, 9, 22 ,34 ,11 ,8 ,15 ,13, 2 ,55);
list1.stream()
.filter( i -> i > 12)
.forEach( i -> System.out.print(i + " "));
Output: 18 22 34 15 13 55
产出:18 22 34 15 13 55