簡體   English   中英

如何在java中獲取數組中的第一個和最后一個元素?

[英]How to get first and last element in an array in 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,]

我想獲取第一個元素和最后一個元素,以便

firstNum = 10.2

lastNum = 17.5

我該怎么做?

如果您有一個名為numbers的雙數組,則可以使用:

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

或使用ArrayList

firstNum = numbers.get(0);
lastNum = numbers.get(numbers.size() - 1); 

在Java中獲取數組中的第一個和最后一個元素

int[] a = new int[]{1, 8, 5, 9, 4};

First Element: a[0]

Last Element: a[a.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

這在任何數組中都是一樣的。

檢查這個

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

我認為只有一種直觀的解決方案,它是:

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);

輸出:

First: 1
Last: 5

在java中獲取數組中的第一個和最后一個元素

double[] numbers = {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,};


double firstNumber= numbers[0];

double lastNumber = numbers[numbers.length-1];

System.out.println("firstNum = "+ firstNumber);

System.out.println("lastNum = "+ lastNumber);

這是給定的數組。

    int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};

// 如果要打印數組中的最后一個元素。

    int lastNumerOfArray= myIntegerNumbers[9];
    Log.i("MyTag", lastNumerOfArray + "");

// 如果要打印數組中元素的數量。

    Log.i("MyTag", "The number of elements inside" +
            "the array " +myIntegerNumbers.length);

// 打印數組中最后一個元素的第二種方法。

    Log.i("MyTag", "The last elements inside " +
            "the array " + myIntegerNumbers[myIntegerNumbers.length-1]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM