【问题标题】:How to use int from other class? [duplicate]如何使用其他类的 int? [复制]
【发布时间】:2015-09-14 16:14:43
【问题描述】:

这是我的主要方法:

public class Main {

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

这是我的另一堂课:

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;

    }
}

我希望能够在 main 方法中使用两个 Ints f 和 s(第一个和第二个)。

如果这是一个愚蠢的问题,我只想能够使用 getter/从 main 方法调用 give 方法。我该怎么做?

我是编码新手,所以假设我几乎一无所知。解释得很透彻。谢谢!

EDIT - 代码应该采用两个整数并返回总和。

【问题讨论】:

  • 也许你可以看看DTO是什么,它可以帮助你
  • 代码甚至无法编译。 fsin main 未声明。你想做什么?得到两个整数的和?那你为什么返回Object而不是intlook应该怎么做?
  • this 可能会有所帮助,但我建议您阅读一本基本的 Java 书籍...
  • 你能编辑你的问题并解释你的代码应该实现什么吗?原来的任务是什么?并解释你的每种方法在该作业中应该做什么?
  • @RealSkeptic - 我现在就这样做。

标签: java methods int getter


【解决方案1】:

您可以通过将变量 f 和 s 设置为实例变量来做到这一点。您可以通过在 Comp 类中进行这样的设置来做到这一点:

public int f;
public int s;

然后您可以通过在 main 中执行此操作来引用每个变量:

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

【讨论】:

    【解决方案2】:

    所以您需要look 方法来返回输入整数以及这些整数的总和。

    所以让我们创建一个类来包含这些信息:

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

    【讨论】:

    • 首先,我认为您的解决方案超出了 OP 的范畴。我认为 OP 的问题是不知道如何使用参数和返回值——数据如何通过调用流动。第二 - fs 没有在 main 中定义,所以我们回到第 1 格。
    猜你喜欢
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多