-1
public class raceCar{
    private String driver;
    private String car;

    public raceCar(String driver, String car){
        this.driver = driver;
        this.car = car;
    }
}

I need to pass in two strings in the constructor, but the constructor needs to check that the string is a number between 0 and 99, If it is not, set it to "00".

Beau Grantham
  • 3,435
  • 5
  • 33
  • 43
user2905087
  • 11
  • 1
  • 1
  • [Convert int to string](http://stackoverflow.com/questions/5585779/how-to-convert-string-to-int-in-java), [basic if-then tutorial](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html). – rutter Oct 21 '13 at 23:59

3 Answers3

3

To test, use regex:

if (str.matches("[1-9]?\\d")) {
    // it's a number between 0 and 99
}

This works by using a regular expression to check the string. The parts of the expression are:

  • [1-9]? a single character in the range 1 to 9, made optional by the ?
  • \d any digit

The regex could have been \d\d, but that would have allowed "00".

FYI, in java String.matches() only returns true if the entire String matches the pattern, so no need for ^ and $. This is unlike many other languages that return true for a partial match.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

You could convert your string to an int using Integer.parseInt() and then use an if-statement to check if its both greater then -1 and less then 100.

Beau Grantham
  • 3,435
  • 5
  • 33
  • 43
sirFunkenstine
  • 8,135
  • 6
  • 40
  • 57
0
public class raceCar
{
    private String driver;
    private String car;

    public raceCar(String driver, String car)
    {
        if (Integer.parseInt(driver) < 100 && Integer.parseInt(driver) >= 0)
            this.driver = driver;
        else
            this.driver = "00";

        if (Integer.parseInt(car) < 100 && Integer.parseInt(car) >= 0)
            this.car = car;
        else
            this.car = "00";
    }
Whoppa
  • 949
  • 3
  • 13
  • 23