如何在Java中找到数组中字符串的索引号

时间:2013-02-15 19:34:17

标签: java arrays input

我不知道我是否有效编码,甚至是正确编码,但我想输入姓名,地址和电话号码。然后,我希望输入从输入数组中找到匹配项,并使用相同的索引号打印相应的信息。

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++;
        } 
    }

}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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数组。

答案 2 :(得分:0)

好像你已经完成了数据输入。

对于通过搜索进行的数据检索,如果你不关心效率,那么你可以迭代整个数组,看看输入的文本是否与数组中的任何元素匹配

int searchIndex = 0;
for (int i = 0; i < names.length; i++) {
    if (searchString.equals(names[i])) {
        searchIndex = i;
    }
}

其中searchString是用户输入的字符串,用于查找数组中的元素。上面的代码块假设您没有重复数据,但如果您愿意,您可以轻松调整返回的索引以包含包含数据的索引数组。然后,您可以使用索引号(或索引号)来查找其他数组中的其余数据。