2015-04-19 53 views
0

我需要在java中的类的方法中通过t1t2。我只展示了相关的部分。在类方法中传递变量

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)")); 
} 

的类如波纹管

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

我收到以下错误int result_hr = t1.hr + t2.hr; int cannot be deference

+1

如果't1'和't2'是'int's,那么它们不是'Time's,并且不会有'hr'字段。 – azurefrog

+0

该方法的声明不应该像'public static int add2times(Time t1,Time t2)'?你希望't1'和't2'是'Time'对象,对吗? –

+0

最少阅读http://docs.oracle.com/javase/tutorial/ –

回答

3

你得到是说,T1和T2的错误不是对象,并没有hr变量,这是因为对象t1和t2是Time对象,因此需要在参数中声明。您目前正在将它们定义为int。

您的add2Times方法也不会返回结果时间。我修正了这个问题。

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

现在我觉得很傻 – user2650277

+0

该方法确实应该声明为“静态”。 –

+0

@DavidWallace我知道。但这不是代码审查。 –