2013-02-15 247 views
0

我不知道我是否有效地編寫了該代碼,或者甚至沒有問題,但是我想輸入名稱,地址和電話號碼。然後我想要輸入從輸入數組中找到匹配項,並使用相同的索引號打印相應的信息。如何在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++; 
     } 
    } 

} 

回答

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陣列爲其他顯示。

+0

這很好,謝謝。 – user2076744 2013-02-15 20:13:26

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

看來你已經完成了數據輸入。

至於數據檢索通過搜索,如果你不關心效率,那麼你可以將整個陣列上重複,以查看是否輸入文本使用

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

其中搜索字符串數組中的任何元素相匹配將是由用戶輸入的字符串來查找數組中的元素。上面的代碼塊假設您沒有重複的數據,但如果願意,您可以輕鬆地調整返回的索引以包含包含數據的索引數組。然後你會得到一個索引號(或索引號),你可以用它來查找其他數組中的其餘數據。

相關問題