[英]how to find index of String Array accepted by user in java?
Accept the string from user eg:[Aamir,Hrithik,Salman] Now when i pass Hrithik it should return its index? 接受来自用户的字符串,例如:[Aamir,Hrithik,Salman]现在,当我通过Hrithik时,它应该返回其索引吗? How? 怎么样?
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);
}
}
Checking a single element of the array arr[i].equals(check)
doesn't help much. 检查数组arr[i].equals(check)
的单个元素没有太大帮助。 Note that i
hasn't been reset from the previous loop execution, you might get an invalid array index ( i >= arr.length
). 请注意, i
没有从上一个循环执行中复位,您可能会得到无效的数组索引( i >= arr.length
)。
You'd better iterate over all the elements of the array to look for a match: 您最好遍历数组的所有元素以寻找匹配项:
for(i = 0; i < str; ++i) {
if (arr[i].equals(check)) {
System.out.println(i);
break;
}
}
Transform the array to a list then use indexOf
method. 将数组转换为列表,然后使用indexOf
方法。
String[] arr = {"Aamir","Hrithik","Salman"};
String target = "Hrithik";
System.out.println(Arrays.asList(arr).indexOf(target));
You need to add a for loop at the end to loop through the entire array. 您需要在末尾添加一个for循环以遍历整个数组。 The following code should work. 下面的代码应该工作。 I have also made some other edits that make the code generally better. 我还进行了一些其他编辑,使代码通常更好。
Side note: you should format your code a bit better to make it more readable. 旁注:您应该更好地格式化代码,以使其更具可读性。 On most IDEs, you can auto format code using CTRL/CMD+SHIFT+F . 在大多数IDE上,您可以使用CTRL / CMD + SHIFT + F自动格式化代码。
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(arr[i]);
}
System.out.println("Enter the name to check index of it:");
check = sc.next();
for (int j = 0; j < str; j++) {
if (arr[j].equals(check)) {
System.out.println(j);
break;
}
}
}
There are multiple ways to return the index of a value inside an array. 有多种方法可以返回数组内的值的索引。 You can: 您可以:
Use a loop: 使用循环:
for (i = 0; i < str; i++) {
if (arr[i].equals(check)) {
System.out.println("Index of value: " + i);
break;
}
}
Use the Arrays
utility class: 使用Arrays
实用程序类:
System.out.println("Index of value: " + Arrays.asList(arr).indexOf(check));
Use the Apache Commons Lang ArrayUtils
class: 使用Apache Commons Lang ArrayUtils
类:
System.out.println("Index of value: " + ArrayUtils.indexOf(arr, check));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.