1

How can I make my setter method public void setYear(String year) check if the input is a number or not? It's for a class exercise. I'm just trying to understand why/how to do this. I don't know why, but it has to be string year, and I need to make sure that only a number can be used.

For example I have:

public void setColour(String colour) {
    colour = colour;
}
karel
  • 5,489
  • 46
  • 45
  • 50
Ryan
  • 21
  • 2

3 Answers3

2
public void setYear(String year) {
       if (Integer.parseInt(year) >= 0) {
           //Do stuff here
       }
}

Use Integer.parseInt(String s) to check if String year can be convert to an Integer greater or equal to zero (logically, a year can not be negative). If the input can not be converted to an Integer, it will throw a NumberFormatException.

vs97
  • 5,765
  • 3
  • 28
  • 41
1

I can propose 2 ways of doing this.
Suppose the string you need to validate is strYear and you consider valid all integer values >= 0.
The 1st is by forcing the string to be casted to an integer and catching any error thrown:

int year = -1;
try {
    year = Integer.parseInt(strYear);
} catch (NumberFormatException e) {
    e.printStackTrace();
}
boolean validYear = (year >= 0);

The 2nd is eliminating all non numeric chars in the string and compare the result to the original string. If they are the same then the string consists only of digits:

strYear = strYear.trim();
String strOnlyDigits = strYear.replaceAll("\\D", "");
boolean validYear = (!strYear.isEmpty() && strYear.equals(strOnlyDigits));
forpas
  • 160,666
  • 10
  • 38
  • 76
1
public int year;

public void setYear(String year){
   try {
      year = Integer.parseInt(year);
   } catch(Exception e) {
       e.printStackTrace();
   }
}

You can use try and catch to check if the input is a number. In here, you are trying to parse the String into integer. If it only contains a number, it will be able to convert it successfully. On the other hand, if it has some other characters, it will stop and you will get an exception. Try and catch prevents your program from crashing.

At the same time, you can try regular expression to check if it only contains number.

String regex = "[0-9]+";
year.matches(regex );
Semjerome
  • 43
  • 6