接受用户的字符串,例如:[Aamir,Hrithik,Salman] 现在,当我通过 Hrithik 时,它应该返回其索引? 怎么办?
public static void main(String[] args)
{
int str,i;
String check;
Scanner sc=new Scanner(System.in);
System.out.println("Enter string array size: ");
str=sc.nextInt();
String arr[]= new String[str];
System.out.println("Enter elements for String array: ");
for(i=0;i<str;i++)
{
arr[i] = sc.next();
}
System.out.println(Arrays.toString(arr));
System.out.println("Enter the name to check index of it:");
check=sc.next();
if(arr[i].equals(check))
{
System.out.println(i);
}
}
最佳答案
有多种方法可以返回数组内值的索引。您可以:
使用循环:
for (i = 0; i < str; i++) {
if (arr[i].equals(check)) {
System.out.println("Index of value: " + i);
break;
}
}
使用Arrays
实用程序类:
System.out.println("Index of value: " + Arrays.asList(arr).indexOf(check));
使用 Apache Commons Lang ArrayUtils
类:
System.out.println("Index of value: " + ArrayUtils.indexOf(arr, check));
关于java - 如何在java中找到用户接受的字符串数组的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51685390/