[英]How do you find the index number of a string in an array in Java
我不知道我是否在有效地編碼甚至正確編碼,但是我想輸入姓名,地址和電話號碼。 然后,我想讓輸入從輸入數組中找到一個匹配項,並使用相同的索引號來打印相應的信息。
import java.util.*;
public class NameAddress {
public static void main(String[] args) {
Scanner ui = new Scanner(System.in);
System.out.println("Welcome to the name collecting database");
String []names = new String[5];
String []address = new String[5];
String []phone = new String [5];
int count =0;
while (count<=5)
{
System.out.println("Please enter the name you would like to input");
names[count] =ui.next();
System.out.println("Name has been registered into Slot "+(count+1)+" :"+Arrays.toString(names));
System.out.println("Please enter the address corresponding with this name");
ui.nextLine();
address[count] = ui.nextLine();
System.out.println(names[count]+" has inputted the address: "+address[count]+"\nPlease input your phone number");
phone[count]=ui.nextLine();
System.out.println(names[count]+"'s phone number is: "+phone[count]+"\nWould you like to add a new user? (Yes or No)");
if (ui.next().equals("No"))
{
System.out.println("Please enter a name to see matched information");
String name = ui.next();
if(name.equals(names[count]))
{
System.out.println("Name: "+names[count]+"\nAddress: "+address[count]+"\nPhone: "+phone[count]);
}
count=6;
}
count++;
}
}
}
System.out.println("Please enter a name to see matched information");
String name = ui.next();
for(int i = 0; i <names.length;i++){
if(name.equals(names[i]))
{
System.out.println("Name: "+names[i]+"\nAddress: "+address[i]+"\nPhone: "+phone[i]);
}
}
if(name.equals(names[count]))
將工作僅當name
用戶搜索的是在當前索引names
。 因此,您必須檢查數組中的每個項目,以確定它是否存在於數組中。 你可以這樣做:
int itemIndex = Arrays.asList(names).indexOf(name);
if(itemIndex>=0) // instead of if(name.equals(names[count]))
{
// rest of the codes; use the itemIndex to retrieve other information
}
else
{
System.out.println(name + " was not found");
}
或者像其他人一樣手動遍歷names
數組。
似乎您已經完成了數據輸入。
至於通過搜索進行數據檢索,如果您不關心效率,則可以遍歷整個數組,以查看輸入的文本是否與您使用的數組中的任何元素匹配
int searchIndex = 0;
for (int i = 0; i < names.length; i++) {
if (searchString.equals(names[i])) {
searchIndex = i;
}
}
其中searchString是用戶輸入的用於在數組中查找元素的字符串。 上面的代碼塊假定您沒有重復的數據,但是您可以根據需要輕松地調整返回的索引以包含包含數據的索引數組。 然后,您將擁有一個索引號(或多個索引號),可用於查找其他數組中的其余數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.