【问题标题】:How can I call a method from another class with integers in it? [closed]如何从另一个类中调用带有整数的方法? [关闭]
【发布时间】:2020-10-26 00:08:26
【问题描述】:

基本上,我有这两个类:

public class Main {
    public static void main(String[] args) {
        int units = 0;
        int tenth = 0;
        int hunds = 0;
        int thousands = 0;
        Nums met = new Nums();
        System.out.println("Insert 4-digit number ");
        met.set_nums();
        System.out.println("The number " + num + " in reverse is " + units + tenth + hunds + thousands);
    }
}

public class Nums {
    Scanner in = new Scanner(System.in);
    int num;
    int thousands;
    int hunds;
    int tenths;
    int units;
    public void set_nums(int num, int thousands, int hunds, int tenths, int units) {
        num = in .nextInt();
        thousands = num / 1000;
        hunds = num / 100 - ((num / 1000) * 10);
        tenths = num / 10 - ((num / 100) * 10);
        units = num - ((num / 10) * 10);
    }
}

我需要让程序扫描数字,然后在第二类中进行操作,以便它可以将数字反转。如何让主类调用整数并在操作后显示数字?我尝试过其他方法,例如将整数放在头等舱和扫描仪中,但这些都没有奏效。我能做什么?

【问题讨论】:

  • 欢迎来到 SO。 “调出整数并显示数字”是什么意思。 “呼出”是指“从终端读取”,“显示”是指“打印”吗?您似乎有未使用的 set_nums 方法的参数。它们是干什么用的?
  • @sprinter 请解释您对问题的编辑。删除 import 语句不是“格式化”。为什么要添加所有空格,尤其是in .nextInt() 中的空格?
  • import 语句是代码的必要部分。
  • nums类有import语句,只是我复制的时候没有出来。程序需要做的是:扫描数字,进行操作,结果必须分配给整数,以便打印在主类中

标签: java class methods


【解决方案1】:

您的代码中有很多错误。毕竟,我相信它不会编译(我没有尝试过),因为方法 set_nums 是在没有参数的情况下调用的,并且它被声明为接收 4 个 int 参数。

即使你在Main类中传递变量,它也不起作用,因为在Java中,参数是按值传递的,并且更改不会返回。

要使该代码有效,您需要:

  1. 从 Main 类中删除单位、十、百和千的声明。

  2. 从 set_nums 方法声明中删除所有参数。

  3. 在 Nums 类上打印实例中的值:

    System.out.println("数字"+num+"反过来就是"+met.units + met.tenths + met.hunds + met.thousands);

为了更好的编码风格,将 Scanner 实例化移动到 Main 类并在那里调用 nextInt,将扫描的数字传递给 set_nums。

【讨论】:

  • 请发布包含您所做更改的完整代码副本。另一个用户曾经要求我这样做,尽管我的更改非常简单;您的更改要复杂得多。
猜你喜欢
  • 2014-03-15
  • 1970-01-01
  • 2016-06-14
  • 2013-03-05
  • 2014-03-17
  • 1970-01-01
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多