【问题标题】:How to pass an array and an int trough classes and methods?如何通过类和方法传递数组和int?
【发布时间】:2016-07-30 13:37:44
【问题描述】:

我试图让编译器将数组从其中一个类传递给 main 方法。不知道为什么不行,代码是这样的:

这是我的主要方法 -

public class Main {
    public static void main(String[] args) {

        int[] board2;
        int userInput;
        playBoard = methods.createBoard();
        userInput = methods.input();



    }

}

这是我的方法类 -

import java.util.Scanner;

public class methods {

        //Create board method

    int[] createBoard()
    {
        int[] board = new int[7];
        int randomNum =(int) (Math.random()*5);
        for (int i=0; i<2; i++)
        {
            board[randomNum+i] = 1;
        }
        System.out.println("Board created");
        return board;
    }

        //Take a guess method


    int input()
        {
            int input=0;
            Scanner reader = new Scanner(System.in);
            System.out.println("Please enter your guess now");
            input = reader.nextInt();
            System.out.println("Guess entered successfully");
            return input;
        }

}

我知道我可以轻松地将所有内容放在一个类甚至一个方法中,但我要练习使用类和方法,因此我创建了很多。

【问题讨论】:

  • 你需要先创建类对象来调用方法(如果方法不是静态的)尝试playBoard = new methods().createBoard();和其他数组一样
  • 谢谢,我通过将方法设为静态来解决问题。

标签: java arrays class methods


【解决方案1】:

您必须首先创建Mainmethods 的新实例,或者将createBoard()input() 方法声明为静态。

这里是sn-p的代码:

public class Main {
    public static void main(String[] args) {
        Main m = new Main();
        m.run();
    }

    private void run() {
        methods me = new methods();
        int[] playBoard = me.createBoard();
        int userInput = me.input();
    }
}

此外,根据类名的命名约定规则,它应该是 Methods 而不是 methods

【讨论】:

    【解决方案2】:

    您还没有声明变量 playBoard 在Main 中使用。您是否打算改用 board2。我猜你想要类似下面的东西:

    board2 = new methods().createBoard();
    userInput = new methods().input();
    

    您需要创建一个methods 类的对象,才能访问实例方法。

    【讨论】:

      猜你喜欢
      • 2012-11-12
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2018-09-27
      • 1970-01-01
      相关资源
      最近更新 更多