How to use int from other class?

时间:2015-09-14 16:14:43

标签: java methods int getter

Here is my main method:

public class Main {

    public static void main(String[] args){
        Comp.give(f, s);
    }
}

And here is my other class:

import java.util.Scanner;

public class Comp {
    private void look() {
        Scanner iscan = new Scanner(System.in);
        int f = iscan.nextInt();
        int s = iscan.nextInt();
    }

    public static Object give(int f, int s) {
        return f + s;

    }
}

I'd like to be able to use the two Ints f and s (first and second) in the main method.

And if that's a stupid question, I'd just like to be able to use a getter/call the give method from the main method. How do I do this?

I'm new to coding, so assume that I know next to nothing. Explain very thoroughly. Thanks!

EDIT - Code is supposed to take two ints and return the sum.

2 个答案:

答案 0 :(得分:1)

您可以通过将变量f和s设置为实例变量来完成此操作。您可以通过在Comp类中设置如此设置:

public int f;
public int s;

然后你可以在main中执行以下操作来引用每个变量:

Comp example = new Comp();
int f = example.f;
int s = example.s;

答案 1 :(得分:0)

所以你需要look方法来返回输入的int以及这些int的总和。

因此,让我们创建一个包含此信息的类:

public class IntsAndSum {
    private List<Integer> ints;
    private int sum;
    // constructor
    public IntsAndSum(List<Integer> ints, int sum) {
        this.ints = ints;
        this.sum = sum;
    }
    // + getters
}

现在让我们写look,以便它返回IntsAndSum的实例:

private IntsAndSum look(){
    Scanner iscan = new Scanner(System.in);
    int f = iscan.nextInt();
    int s = iscan.nextInt();
    // let's put them into a List<Integer>
    List<Integer> ints = new ArrayList<>();
    ints.add(f);
    ints.add(s);
    // let's compute the sum
    int sum = f + s;
    // let's return a new IntsAndSum
    return new IntsAndSum(ints, sum);
}

现在您可以使用main方法访问信息:

public static void main(String[] args){
    IntsAndSum is = Comp.give(f, s);
    // let's print the numbers:
    for(int n : is.getInts()) {
        System.out.println(n);
    }
    // let's print the sum
    System.out.println("sum is: " + is.getSum());
}