2016-10-04 13 views
7

Jeśli mam tablicę podwaja:Jak uzyskać pierwszy i ostatni element tablicy w java?

[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,] 

i chcę dostać pierwszy element i ostatni element, tak aby

firstNum = 10.2 

lastNum = 17.5 

w jaki sposób mogę to zrobić?

Odpowiedz

15

Jeśli masz podwójną tablicę o nazwie numbers, można użyć:

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

Dodanie odniesienia dokumentacji, aby odpowiedź pełniejsze: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – acoelhosantos

1
// 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 

To jest taka sama w każdej tablicy.

0

Sprawdź to

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