1

I have an class called car with attributes and one of those attributes being a license number which I have to show printed and it must fulfil being only 6 chars long and having 3 characters and 3 numbers as such: ASF817

Also if somebody inputted their license plate number being wrong, how would I tell print some code to say it is wrong?

I'm not sure of what method to use at all to restrict to exactly specific values.

public class Car {
private String regNo;
private String make;
private String model;
private String driverName;
private int passengerCapacity;
private boolean available;
private String[] Booking = {"currentBookings, pastBookings"};

public Car(String regNo, String make, String model, 
String driverName, int passengerCapacity) {
    this.regNo = regNo;
    this.make = make;
    this.model = model;
    this.driverName = driverName;
    if(passengerCapacity < 0) 
    {
        this.passengerCapacity = 1;
    }
    else if(passengerCapacity > 10) 
    {
        this.passengerCapacity = 10;
    }
    else 
    {
        this.passengerCapacity = passengerCapacity;
    } 
    System.out.println(this.passengerCapacity);

Need to make String regNo only be 6 chars, with 3 characters first and 3 numeric values after when inputted by a user. Thank you.

Ayriana
  • 19
  • 1
  • 1
    What you describe is called validation. One of the most basic ways to do that would be to do the checks in the setter and/or constructor and throwing an exception if the check fails. – Thomas Apr 18 '19 at 12:59
  • 1
    A simple [regex comparison](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html) would work (`/[A-Z]{3}[0-9]{3}/`) but you would have to do that when getting the user input or else throw an exception in the constructor. – 001 Apr 18 '19 at 13:01
  • @Thomas how would i do this? I find it hard to navigate the web and get information that relates to this. Im a bit lost sorry – Ayriana Apr 18 '19 at 13:09
  • 1
    How would you do what? The check itself? That would be by using some regex, e.g. `regNo.matches("[A-Z]{3}[0-9]{3}")`. Throwing an exception if the check fails? That would be something like `throw new SomeException()` - and you might want to read up on exceptions in general first if you're not familiar with them yet. – Thomas Apr 18 '19 at 13:49
  • Check this post, they have an example there that will help you: https://stackoverflow.com/questions/30803650/java-how-to-only-create-an-object-with-valid-attributes – Laguh Apr 18 '19 at 15:29

0 Answers0