简体   繁体   中英

The operator > is undefined for the argument type(s) void, void

Hi, I get the error in title with this java code

public static void age(Ship ob){
    DateTime myBirthDate = ob.getDate();
    DateTime now = new DateTime();
    Period period = new Period(myBirthDate, now);

    System.out.print("Ship age is " + ob.getName() + " е " );

    PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendYears().appendSuffix(" years") 
        .appendMonths().appendSuffix(" months") 
        .appendWeeks().appendSuffix(" weeks") 
        .appendDays().appendSuffix(" days")
        .appendHours().appendSuffix(" hours")
        .appendMinutes().appendSuffix(" mnutes")       
        .appendSeconds().appendSuffix(" seconds\n ")
        .printZeroNever().toFormatter();

    String elapsed = formatter.print(period);
    System.out.println(elapsed);
}

public static void compare(Ship ob, Ship ob2) throws ParseException {
    if(age(ob2) > age(ob)){ //<---- I get the Error here , when i try to comapre two objects
        System.out.println( "The ship,wich is more years is " + ob2);
    } else
        System.out.println( "The ship,wich is more years is " + ob);
}

Can you help me? I tried many ways to fix this error but nothing helps, thanks.

Error is happening because you are trying to compare two void (s) using > operator in the following statement:

if(age(ob2) > age(ob))

your age method returns void as mentioned here:

public static void age(Ship ob)

You probably should return an integer value from age, which will make your comparison logical.

Your'e comparing two void return values. You should return an integer in age method, and probably change its logic.

int compareResult = ob.getDate().compareTo(ob2.getDate());
if (compareResult > 0) //ob2 date after ob date
    else if (compareResult < 0) //ob2 date before ob
        else //ob2 has same date as ob

Calculating age like this ain't good if you want to practice OOP. You should make an age method a member of Ship class. And/or have a comparison method in Ship class that accepts another Ship and returns result of date/age compare.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM