1

I am still learning but seem to fall at what should be very simple hurdles; my strong points seem to be with the logic of equations but I possess little skill at remembering and implementing functions and correct simple syntax's.

The class that I am implementing the method in is MyClass, the method that I want to define the variable taken from the other class is establishIrEvent. The class that I want to collect the variable from is IREvent, the getter method that returns the variable in this class that I want to collect is getX.

Now for the code:

Getter method from IREvent class:

public int getX() {
    return x;
}

Method that I want to use that variable in to assign, (with my terribly poor attempt) in MyClass:

public void establishIrEvent(IREvent arg0) {

    int source = (IREvent)arg0.getX();

}

Any advice will be hugely appreciated and fingers crossed this question may aid someone else in a similar pickle! Please ask for any more info as I always seem to miss something or ask a question that annoys an experienced developer somewhat.

4

4 回答 4

3

您的代码有几个问题。首先,您尝试将 an 分配int给 aString因为getX返回int并且source变量是 a String。如果您想这样做,请尝试:

String source = Integer.toString(arg0.getX());

其次,也不是什么大问题,没有必要强制arg0转换为,IREvent因为它已经在establishIrEvent方法中定义了。

于 2013-05-17T13:47:49.037 回答
1

getX()返回一个 int 以便您可以执行以下操作

public void establishIrEvent(IREvent arg0) {

   int x = arg0.getX(); // local variable x which is the x from the IREvent class
   String source = Integer.toString(x); // if that's what the source string should be given x

}

该代码应该可以编译并运行,但它仍然没用,因为调用不会改变任何内容establishIrEvent(IREvent arg0),因为变量 x 和 source 在调用后都被丢弃了。因此,您可能希望将x和/或source变量作为方法所在类的成员变量establishIrEvent(IREvent arg0)

于 2013-05-17T13:48:52.983 回答
1

下面的语句有问题:

String source = (IREvent)arg0.getX();

问题:IREvent 的 getX() 方法正在返回 int,而您正试图通过将返回类型转换为 IREvent 来将其分配给 String。最终让每个人都感到困惑,包括 JVM 和你自己。

如果是这种情况,我不确定您是否需要将值作为 String ,那么您需要这样做:

String source = String.valueOf(arg0.getX());
于 2013-05-17T13:48:54.437 回答
1

你已经完成了大部分工作。事情是arg0.getX()返回一个int. 这int不是您分配给它的字符串,因此您必须将其转换为int类型。您尝试将其转换(类型转换)IREvent为错误的类型。尝试这样的事情:

public void establishIrEvent(IREvent arg0) {
     String source = String.valueOf(arg0.getX());
} 

我建议您使用 Eclipse IDE,所有这些东西都会更容易处理。Eclipse IDE 将为您提供即时的编译器错误和警告消息并提出好的建议。

于 2013-05-17T13:49:52.107 回答