我如何使用一个变量来调用方法中的方法呢?

时间:2016-03-26 23:57:27

标签: java

我只是想知道如何使用在方法本身中调用方法的变量。例如,如果我有一个方法public void addTwo,它为调用它的变量添加2,我如何使用在代码中调用它的变量来向它添加2?

public void addTwo(){
     //add two to the variable that calls
     //This is where i need help
}
public static void main(String[] args){
    int x = 3;
    x.addTwo();
    S.O.P(x);
}

它会打印5

4 个答案:

答案 0 :(得分:1)

我不确定你为什么要朝这个方向前进,但我建议你避免它。

符号x.y()用于调用对象x的方法y。如果将x声明为int,它将是原始类型,因此不会有任何个性化方法。

你可以做的是创建一个新的类,其中包含一个嵌入整数的个性化方法:

public class StackOverflowInt{
  private int x;

  public StackOverflowInt(int value) {
    this.x = value;
  }

  public int addTwo(){
    return this.x+2;
  }
}

然后使用此类来实现结果:

public static void main(String[] args) {
    StackOverflowInt integer = new StackOverflowInt(3);
    System.out.println(integer.addTwo());
}

这将打印5。

另一种替代实现如下:

public class StackOverflowInt{
private int x;

public StackOverflowInt(int value) {
    this.x = value;
}

public void addTwo(){
    this.x = this.x+2;
}

@Override
public String toString(){
    return String.valueOf(x);
}
}

然后:

    public static void main(String[] args) {
     StackOverflowInt integer = new StackOverflowInt(3);
     integer.addTwo();
     System.out.println(integer); //prints 5
    }

答案 1 :(得分:0)

您可能想要做的是:

public static int addTwo(int x){
     return x + 2;
}

public static void main(String[] args){
    int x = 3;
    x = addTwo(x);
    S.O.P(x);
}

您只能通过实例(例如x.addTwo())调用方法,如果它属于实例的类和/或可访问。由于x属于原始类型(而不是类),因此您无法x.addTwo()

答案 2 :(得分:0)

正如@ElliottFrisch所提到的,你不能在原始数据类型上调用方法。从你想要做的事情来看,你需要让你的" addTwo"方法取并返回一个int。

public static int addTwo(int n) {
  return n + 2;
}

然后将结果分配给变量x

int x = 1;
x = addTwo(x);

答案 3 :(得分:0)

在Java中,int是一种基本类型,而不是一个对象。所以,你不能写x.addTwo() 以下课程可能适合您:

public class MyInt {
    private int value;

    public MyInt(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public void addTwo() {
        value += 2;
    }
}

然后,您可以按如下方式使用它:

x = new MyInt(3);
x.addTwo();
System.out.println(x.getValue());