将整数从一种方法传递到另一种方法

时间:2015-10-02 00:01:35

标签: java class variables methods

我试图将一个方法中的三个整数传递给Java中同一个类中的另一个方法。

我当前的代码看起来像这样(但简化了):

import java.util.Scanner;

public class One()
{
    int var1 = 33;
    int var2 = 34;      //these three have to sum to 100
    int var3 = 33;

    //this is in a while loop in case the three numbers != 100
    public int two()
    {
        Scanner in = new Scanner(System.in);
        //let user change var1, var2, var3 if they want
        if (var1 + var2 + var3 == 100)
        {
            //I would guess the code for passing the variables is here
            break;
        }
        //else statement
    }

    public int three()
    {
         //transfer var1, var2, var3 here and do stuff with it
    }
}

我看了这个,显然我必须创建一个对象或一个数组来将它们传递给另一个方法(?)。但是,我觉得有一种更简单的方法可以做到这一点,因为我班上只有两种方法。

3 个答案:

答案 0 :(得分:0)

import java.util.Scanner;

public class One()
{
    int var1 = 33
    int var2 = 34      //these three have to equal 100
    int var3 = 33

    //this is in a while loop incase the three numbers != 100
    public int two()
    {
        Scanner in = new Scanner(System.in);
        //let user change var1, var2, var3 if they want
        if (var1 + var2 + var3 == 100)
        {
            three(var1,var2,var3); //call the method, supplying the 3 parameters
        }
        //else statement
    }

    public int three(int var1, int var2, int var3) //declare your method parameters
    {
         //transfer var1, var2, var3 here and do stuff with it
         return 0;//return an int
    }

答案 1 :(得分:0)

您可以按照以下方式执行此操作:

import java.util.Scanner;

public class One {

int var1 = 33;
int var2 = 34;      //these three have to equal 100
int var3 = 33;

Scanner sc = new Scanner(System.in);

public void two() {
    if (var1 + var2 + var3 == 100) {
        three(var1, var2, var3);
    }
    //else statement
}

public void three(int a, int b, int c) {
    //transfer var1, var2, var3 here and do stuff with it
    System.out.println(a);
}

public static void main(String args[]){
    new One().two();
}
}

此外,

  1. 与方法

  2. 不同,您的班级不应该有圆括号
  3. break语句只允许在loops / switch中使用,

答案 2 :(得分:0)

几点:

  1. 您读取了值但从未使用它们(因此条件始终为真)但这不是问题。
  2. 请记住,当将原始类型(int)传递给方法时:实际传入值的COPY。因此,在方法two()中更改var1将不会更改字段变量var1(类变量)< / LI>
相关问题