如何在java中获取数组中的第一个和最后一个元素?

时间:2022-01-29 21:20:14

If I have an array of doubles:

如果我有一个双精度的数组:

[10.2, 20, 11.1, 21, 31, 12, 22.5, 32, 42, 13.6, 23, 32, 43.3, 53, 14, 24, 34, 44, 54, 64, 15.1, 25, 35, 45, 55, 65.3, 75.4, 16, 26, 17.5,]

and I want to get the first element and last element so that

我想要得到第一个元素和最后一个元素

firstNum = 10.2

lastNum = 17.5

how would I do this?

我该怎么做呢?

3 个解决方案

#1


20  

If you have a double array named numbers, you can use:

如果你有一个双数组命名的数字,你可以使用:

firstNum = numbers[0];
lastNum = numbers[numbers.length-1];

#2


3  

// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};

// First position
double firstNum = array_doubles[0]; // 2.5

// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6

This is the same in any array.

这在任何数组中都是一样的。

#3


0  

Check this

检查这个

double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first

#1


20  

If you have a double array named numbers, you can use:

如果你有一个双数组命名的数字,你可以使用:

firstNum = numbers[0];
lastNum = numbers[numbers.length-1];

#2


3  

// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};

// First position
double firstNum = array_doubles[0]; // 2.5

// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6

This is the same in any array.

这在任何数组中都是一样的。

#3


0  

Check this

检查这个

double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first