【问题标题】:How to declare two variables and run each separately through a method? (java)如何声明两个变量并通过方法分别运行? (爪哇)
【发布时间】:2015-09-29 01:00:21
【问题描述】:

所以对于分配,我必须创建一个应用程序,其main() 方法包含两个变量。在声明变量并为每个变量分配一个整数后,我必须通过相同的 3 种方法运行两者。我在想我必须为变量创建一个类,但老实说不知道从哪里开始。到目前为止,我已经弄清楚了如何通过这些方法运行其中一个整数,但我不能让两者都通过相同的方法。 这是我到目前为止的工作:

public class ArithmeticMethods{
    public class integer
    {
    int firstInteger = 10;
    int secondInteger = 20;
    }
    public static void main(String[] args) {
        displayNumberPlus10();
        displayNumberPlus100();
        displayNumberPlus1000();
        System.out.println(firstInteger + " +" + " 10" + " is " + displayNumberPlus10());
        System.out.println(firstInteger + " +" + " 100" + " is " + displayNumberPlus100());
        System.out.println(firstInteger + " +" + " 1000" + " is " + displayNumberPlus1000());
    }
     public static int displayNumberPlus10() {
        int numberPlus10;
        numberPlus10 = (firstInteger + 10);
        return numberPlus10;
    }
    public static int displayNumberPlus100() {
        int numberPlus100;
        numberPlus100 = (firstInteger + 100);
        return numberPlus100;
    }
    public static int displayNumberPlus1000() {
        int numberPlus1000;
        numberPlus1000 = (firstInteger + 1000);
        return numberPlus1000;
    }
}

现在方法被设置为只运行第一个变量,并且我尝试创建一个类,程序根本不起作用。任何建议将不胜感激。 如果代码看起来很难看,我也很抱歉。我对此很陌生。

【问题讨论】:

  • 你知道如何给你的方法添加参数吗?如果没有,请阅读docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
  • 我阅读了这篇文章,但我认为我不太明白我做错了什么。我知道我必须将方法中的值 firstInteger 更改为同时代表 firstInteger 和 secondInteger 的值,但在那之后,我不知道要更改什么。如果我觉得我很愚蠢,我很抱歉……这对我来说是一种全新的语言。我希望我了解需要更改的内容。

标签: java class methods integer


【解决方案1】:

您需要为方法添加参数。结果应如下所示:

public static int displayNumberPlus10(int input) {
    return (input + 10);
}
...

并且可以这样调用:

int first = 10;
int second = 20;

displayNumberPlus10(first);
displayNumberPlus10(second);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2011-10-20
    • 2015-02-05
    相关资源
    最近更新 更多