Java如何检查用户输入是否在我的数组中

时间:2014-04-03 09:34:36

标签: java arrays indexing contains

我希望用户输入customerIDvideoID(数组中的第一个字段),但我希望程序提醒用户他们输入了我尝试过的错误ID {{ 1}}但不起作用

Arrays.asList(...).contains(...)

我试图使用另一个类中的方法访问它,方法是:

// The video array
videos[0]=new Video("150", "Bagdad by Night", 6.00,         5);
videos[1]=new Video("151", "Lord of the Rings 1", 5.00,         0);

//The customer array
customers [0]= new Customer("9902JI", "Innes    ", 0,43484001);
customers [1]= new Customer("8906RH", "Herbert", 0,43484000);

public static void HireVideo(){

    System.out.println("Enter Customer ID");
    String customerID = sc.next();
    System.out.println("Enter Video ID");
    String videoID = sc.next();

    HireList.add(new Hire(customerID, videoID));
}

1 个答案:

答案 0 :(得分:0)

正如ifLoop所提到的,equalsIgnoreCase()应该可行。此外,对Driver.customers [index]!= null的检查不应该作为For check的一部分,因为如果任何记录返回null,循环将终止,给人的印象是找不到id。但实际上,在该空记录之后可以有一条记录,与条件匹配。更好的是,我们应该确保Customer Array永远不会有一个null的记录。

public int getCustomer(String IdToFind){   
  if(Driver.customers.length > 0) {            
    for (int index = 0; index<Driver.customers.length;index++){
      if (Driver.customers[index].getCustomerID().equalsIgnoreCase(IdToFind))
         return index;         //ID found                                      
     }
    return -1;   //ID not found
   } else {
      return -1  //ID not found, as no customers in driver object
   }                              
}