How to call a method with a variable parameter from the main method?

时间:2017-11-16 11:31:04

标签: java variables methods parameters call

I would like to call the isATens method from my main method but im only able to do that when isATens has no parameter. I'v tried putting the same parameter in the caller, but that does't seem to recognize that either.

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

1 个答案:

答案 0 :(得分:1)

您似乎还没有学到一些Java概念:范围和实例与静态方法。如果您在理解我的以下评论时遇到困难,请阅读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。 / p>