简体   繁体   中英

Passing variable in class methods

I need to pass t1 and t2 in the method of a class in java . I have shown only relevant parts .

public static void main(String[] args) {
      int hr,min,secs;
       Time t1;
       t1 = new Time();
       t1.hr = Integer.parseInt(JOptionPane.showInputDialog("Enter the time(hours)"));
       Time t2;
       t2 = new Time();
       t2.hr = Integer.parseInt(JOptionPane.showInputDialog("Enter the time(hours)"));
}

The class is shown bellow

class Time {
    int hr;
    int add2times(int t1, int t2) {
        int result_hr = t1.hr + t2.hr;
    }
} 

I get the following error int result_hr = t1.hr + t2.hr; int cannot be deference

The error you are getting is saying that t1 and t2 are not objects and do not have the hr variable, this is because objects t1 and t2 are Time objects and thus need to be declared as such in the arguments. You are currently defining them as int.

Your add2Times method is also not returning the resulting time. I have fixed that.

int add2times(Time t1, Time t2) {
    return t1.hr + t2.hr;
}

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