[英]Java how to check if user input is in my array
我希望用户输入customerID
和videoID
(数组中的第一个字段),但我希望程序提醒用户他们输入了错误的 ID 我已经尝试过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));
}
我正在尝试使用另一个类中的方法访问它,该方法是:
public int getCustomer(String IdToFind) {
for (int index = 0; index<Driver.customers.length && Driver.customers[index]!=null;index++) {
if (Driver.customers[index].getCustomerID().equals(IdToFind))
return index; //ID found
}
return -1; //ID not found
}
正如 ifLoop 所提到的,equalsIgnoreCase() 应该可以工作。 此外,Driver.customers[index]!=null 的检查不应作为 For 检查的一部分,因为如果任何记录返回 null,循环将终止,给人的印象是未找到 id。 但实际上,在该空记录之后可以有一条记录,与条件匹配。 更好的是,我们应该确保客户数组永远不会有空记录。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.