在verifyPlate方法中,如何在数组Plates中搜索某个字符串“platenum”,然后将一个布尔值返回给main方法?
import java.util.Scanner;
import java.util.Date;
import java.io.*;
public static boolean verifyPlate(String[] plates, int numCars, Scanner keyboard)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter your plate number: ");
String platenum = s.nextLine();
boolean real=false;
for (int i=0;i!=plates.length;i++)
{
boolean platers = platenum.equals(plates[i]);
if(platers)
{
System.out.println("Your vehicle is registered");
}
else
System.out.println("Your vehicle is not registered");
platers=real;
}
return real;
}
答案 0 :(得分:4)
您只需要一行:
return Arrays.asList(plates).contains(platenum);
如果plate是列表而不是数组,则可以省略对asList的调用。通常,应避免使用数组
答案 1 :(得分:0)
您的方法不起作用,因为real
变量可以在循环中的下一次迭代后重置。试试这个:
public static boolean verifyPlate(String [] plates, int numCars,
Scanner keyboard) {
Scanner s = new Scanner(System.in);
System.out.print("Enter your plate number: ");
String platenum = s.nextLine();
for (int i=0;i!=plates.length;i++){
boolean platers = platenum.equals(plates[i]);
if(platers) {
System.out.println("Your vehicle is registered");
return true;
}
}
System.out.println("Your vehicle is not registered");
return false;
}