0

在 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;
}
4

2 回答 2

4

您只需要 1 行:

return Arrays.asList(plates).contains(platenum);

如果盘子是一个列表而不是一个数组,则可以省略对 asList 的调用。一般来说,要避免使用数组

于 2012-11-23T03:27:15.183 回答
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;
}
于 2012-11-23T03:27:43.783 回答