【问题标题】:How to call a method with a variable parameter from the main method?如何从主方法调用带有可变参数的方法?
【发布时间】:2018-04-29 22:14:14
【问题描述】:

我想从我的 main 方法中调用 isATens 方法,但我只能在 isATens 没有参数时才能这样做。我尝试在调用者中放入相同的参数,但似乎也无法识别。

public class P1L4 {

    public static void main(String[] args) {
        P1L4 main = new P1L4();
        main.run();
        isATens(userInput); //<--- this is what I've tried doing.
    }

    public void run() {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Name a tens and i'll test if it's one under 100.");
        int userInput = scanner.nextInt();
    }

    public boolean isATens(int userInput) {
        System.out.println(userInput);
        switch (userInput) {
            case 10 : case 20 : case 30 : case 40 : case 50 : case 60: case 70: case 80: case 90 :
                isUnderOneHundred(continued);
            default :
                System.out.println("Not under one hundred");
        }
        return true;
    }

    public boolean isUnderOneHundred(int continued) {
        return true;
    }
}

【问题讨论】:

  • userInput 不是变量,也不是值。尝试使用:isATens(5) 或 isATens()。此外,由于 isATens 不是静态方法,因此您需要通过类的实例调用它
  • 你也必须调用 main.isAtens(5)。而 isUnderOneHundred 方法毫无意义。
  • run 方法中:isAtens(userInput)Scanner 阅读之后。
  • @Stultuske userInput 怎么不是变量?不是用 int Userinput =scanner.nextInt(); 声明的吗?
  • local 在你的 run 方法中,是的,但是你尝试在你的 main 方法中使用它,那里是未知的

标签: java variables methods parameters call


【解决方案1】:

有些 Java 概念您显然还没有学过:作用域和实例与静态方法。如果您在理解我的以下 cmets 时遇到困难,请阅读 Java 教科书的相应章节。

int userInput = scanner.nextInt();run() 方法的范围内声明,因此在main() 方法中不可见。如果您想在 run() 方法之外查看 userInput,我会将其设为该方法的返回值:

public int run() {
    ...
    int userInput = scanner.nextInt();
    return userInput;
}

您正在混合使用实例方法和静态方法,而没有任何可见的概念何时使用哪种方法。当你想从静态方法调用实例方法时,你需要在点之前命名实例,所以至少它必须是 main.isATens(userInput); 而不是 isATens(userInput); (在你解决了 userInput 问题之后) .

你的程序逻辑很奇怪,例如如果参数小于 100,我希望像 isUnderOneHundred(int continued) 这样的方法返回 true,但该方法甚至不会查看其参数,并且对于您传入的任何数字都返回 true。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2017-09-02
    相关资源
    最近更新 更多