0

I want to extract people born between two years.

Being year1 = "1990" and year2 = "2000". It seems that >= and <= doesn't work.

How can I compare these two date strings?

static void annesCom(Personne[] pers, int nbElem, String year1, String year2)
{
    int i;
    for(i=0; i < nbElem; i++)
        if(perso[i].year() >= year1 && perso[i].year() <= year2 )
    System.out.printf("Person %d) Born in %s\n", i, pers[i].year());
}
Alvaro Fuentes
  • 16,937
  • 4
  • 56
  • 68
Sandra
  • 77
  • 1
  • 7

5 Answers5

4

You cannot use the <= and >= operators on Strings (or < and >). While you can use == and != on Strings, the results won't be what you expect.

For a numeric quantity, you shouldn't use the String datatype. In your Personne class, change the datatype of the variable that holds the year attribute to int, and the return datatype of the getter method year() to int as well. You can use <=, >=, <, >, ==, and != on int values.

In your annesCom method, accept int values for year1 and year2.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

You can use compareTo method. But I suggest to parse string as integer with Integer.parseInt method and then do a comparison.

talex
  • 17,973
  • 3
  • 29
  • 66
0

Parse the numbers currently contained in strings:

if(perso[i].year() >= Integer.parseInt(year1) && perso[i].year() <= Integer.parseInt(year2) )

The only comparison operator applicable to strings in Java is ==. This checks for reference equality (meaning it will only return true if the strings compared are in fact the same object). This will only yield true for strings with identical content known at compile time, as Java saves space by pointing them to the same object.

EvenLisle
  • 4,672
  • 3
  • 24
  • 47
0

you can pass your String year into Integer.parseInt(), and then compare the integers with >= and <=

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
0

You cannot use >= or <= for a String value. String are different from other primitive values like int, double etc. You can convert String to integer and then compare it by using >= or <=

You modified code will look like this:

static void annesCom(Personne[] pers, int nbElem, String year1, String year2)
{
    int i;
    int year1Int = Integer.parseInt(year1);
    int year2Int = Integer.parseInt(year2);

    for(i = 0; i < nbElem; i++)
    {
        if(perso[i].year() >= year1Int && perso[i].year() <= year2Int)
        {
           System.out.printf("Person %d) Born in %s\n", i, pers[i].year());
        }
    }
}
Deep
  • 108
  • 1
  • 1
  • 12