Wenn ich ein Array von Doubles habe:
[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,]
und ich möchte das erste Element und das letzte Element damit erhalten
firstNum = 10.2
lastNum = 17.5
wie würde ich das machen
Wenn Sie ein doppeltes Array mit dem Namen numbers
haben, können Sie Folgendes verwenden:
firstNum = numbers[0];
lastNum = numbers[numbers.length-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
Dies ist in jedem Array gleich.
Überprüfen Sie dies
double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first
Ich denke, es gibt nur eine intuitive Lösung, und diese ist:
int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);
Ausgabe:
First: 1
Last: 5
Erste und letzte Elemente in einem Array in Java abrufen
int[] a = new int[]{1, 8, 5, 9, 4};
First Element: a[0]
Last Element: a[a.length-1]