如何获得Java中阵列中的最后一个数字与零不同
例如,我有这个数组:
double array1[] = {2.3, 5.0, 4.7, 8.2, 1.8, 9.0, 0, 0, 0, 0, 0, 0};
我想找到数组的最后一个不同于 0 的数字。在这种情况下,我的输出应该是: 9.0
我的代码是:
double array1[] = {2.3, 5.0, 4.7, 8.2, 1.8, 9.0, 0, 0, 0, 0, 0, 0};
double array2[] = array1.length;
double num;
for (int i = 0; i < array1.length; i++){
array2[i] = array1[i];
if(array2 != 0){
num = array[i-1];
}
}
但它不起作用。
我需要强调的是 array1 的大小始终相同。但非零数字可以改变,在任何情况下,所有的零将始终位于数组的末尾。
我还需要有由 array1 获得的 array2。
此外,所有数字始终为正数。
I have for example this array:
double array1[] = {2.3, 5.0, 4.7, 8.2, 1.8, 9.0, 0, 0, 0, 0, 0, 0};
And I want to find the last number of the array different to 0. In this case, my output should be: 9.0
My code is:
double array1[] = {2.3, 5.0, 4.7, 8.2, 1.8, 9.0, 0, 0, 0, 0, 0, 0};
double array2[] = array1.length;
double num;
for (int i = 0; i < array1.length; i++){
array2[i] = array1[i];
if(array2 != 0){
num = array[i-1];
}
}
But it doesn't work.
I need to highlight that the size of the array1 is always the same. But the non-zero numbers can change, in any case, all the zeros will be at the end of the array always.
I need also have array2, obtained by array1.
Furthermore, all the numbers are always positive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要从数组的末尾开始,而不是开始:
You need to start at the end of the array, not the beginning:
这是使用循环和三元运算符的一种方法(
a ? b : c
表示如果 a 为 true,则返回b
,否则返回c
)打印
9.0
Here is one way using a loop and the ternary operator (
a ? b : c
says if a is true returnb
, else returnc
)prints
9.0
tl; dr
doubleStream
不一定是最佳方法,但我们可以使用流。具体来说,
doubleStream
。从我们的数组产生流后,滤除零值。然后通过调用
降低
来检索最后一个元素。我们最终得到了
optionalDouble
对象包含我们的结果double
riginitive或为空,这意味着在我们的原始数组中找不到匹配。转储到控制台。
请参阅此代码在iDeone.com 中实时。。
tl;dr
DoubleStream
Not necessarily the best approach, but we can use streams. Specifically,
DoubleStream
.After producing the stream from our array, filter out zero values. Then retrieve the last element by calling
reduce
.We end up with an
OptionalDouble
object that either contains our resultingdouble
primitive or is empty which means no matches were found in our original array.Dump to console.
See this code run live at IdeOne.com.