Java如何检查用户输入是否在我的数组中
我希望用户输入一个Java如何检查用户输入是否在我的数组中,java,arrays,indexing,contains,Java,Arrays,Indexing,Contains,我希望用户输入一个客户ID和一个视频ID(数组中的第一个字段),但我希望程序提醒用户,他们输入的ID不正确,我尝试了数组。asList(…)。包含(…),但不起作用 // 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
客户ID
和一个视频ID
(数组中的第一个字段),但我希望程序提醒用户,他们输入的ID不正确,我尝试了数组。asList(…)。包含(…)
,但不起作用
// 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
}
public int getCustomer(字符串IdToFind){
对于ifLoop提到的(int index=0;index,equalsIgnoreCase()应该可以工作。还有对Driver.customers[index]的检查!=null不应作为For check的一部分,因为如果任何记录返回null,循环将终止,给人一种找不到id的印象。但实际上,在该null记录之后可能有一条记录,与条件匹配。更好的是,我们应该确保Customer数组中没有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
}
}
public int getCustomer(字符串IdToFind){
如果(Driver.customers.length>0){
对于(int index=0;indexHow)如何查找不正确的id?请澄清!该代码应该可以工作。您确定在getCustomer方法类中检查的数组不是空的吗?您确定输入的id与customers
中的一个id完全匹配吗?根据s参数:可能equalsIgnoreCase()
这里有诀窍吗?