簡體   English   中英

你如何找到數組中元素的索引?

[英]How do you find the index of an element inside of an array?

import java.util.Scanner;
public class Lab6a
{
    public static void main (String args[])
    {
        int a[] = {34, 29, 16, 3};
        for (int i=0; i>=0; i--)
        {
            System.out.println("a[i] = " + a[1]);
        }
    }
}

這將打印出 29。我需要一種方法來在我的數組中搜索 29 並返回它的索引,然后將索引存儲為整數

您可以像這樣找到特定值的索引。!

Integer[] array = {1,2,3,4,5,6};

Arrays.asList(array).indexOf(4);

並在代碼中更改for循環

for (int i = 0; i < array.length; i++)

或者

 for (int i = array.length -1 ; i>=0; i--)
import java.util.Scanner;
    public class Lab6a
    {
        public static void main (String args[])
        {
            int i;
            int a[] = {34, 29, 16, 3};
            for (i=0; i<=3; i++)
            {
                System.out.println("a[i] = " + i);
            }
        }
    }

你也可以在需要的位置寫for(i=0;i<a.length;i++) 。這將從0 to length - 1(ie 4)迭代0 to length - 1(ie 4)

注意:length() 是java.lang.String上的一個方法,僅適用於數組。但是,如果您使用像數組列表這樣的集合,您也可以使用size() ,這是java.util.Collection指定的方法。實際上size有效可以很好地遍歷對象,並且不像length那樣靈活,它主要與常量一起使用。

如果你想保留你的數組,你可以嘗試這樣的事情。

int a[] = {34, 29, 16, 3};
int i=0;
while (i<a.length)
{
    if(a[i] == 29) {
        System.out.println("index of 29 is " + i);
        break;
    }
    i++;
}
import java.util.Scanner;
public class Lab6a
{
    public static void main (String args[])
    {
        int a[] = {34, 29, 16, 3}; // the array
        for (int i = 0; i < a.length; i++) // check for each position in array
        {
            System.out.println(a[i] + " = " + a.indexOf(a[i])); // 34 = 0, 29 = 1 etc.
        }
    }
}

據我了解,您有幾個代碼錯誤。 試試這個代碼(把它放在你的主函數中)。 很可能,它應該可以正常工作。

int a[] = {34, 29, 16, 3};
int index = -1;
for (int i = 0; i < a.length; i++)
{
    if (a[i] ==  29)
    {
        index = i;
        System.out.print("a[" + i + "] = " + a[i]);
    }
}
if (index == -1)
    System.out.print("Such array element not found.")

index變量將存儲您找到的元素的索引值。 如果沒有找到, -1將存儲在那里。

暫無
暫無

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

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