【问题标题】:How can I pass an Array from one class to another?如何将数组从一个类传递到另一个类?
【发布时间】:2016-04-07 09:57:31
【问题描述】:

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

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

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



    }

}





import java.util.Scanner;
public class takeAGuess {
        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;
        }
}







public class board {
    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;
    }
}

我已经尝试过以下几行:

new[] board = board.Createboard();
int board[] = board.Createboard();
{
  int board = new board();
  board  = createBoard();
}

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

【问题讨论】:

  • 请将您的代码作为文本包含在问题中,而不是屏幕截图。
  • 首先,Java 中的类以大写字母命名。您不应该为所有内容编写额外的类。如果你使用你的类板只是为了创建一个数组,只需在主类中编写一个方法,不要为此创建一个自己的类。输入也一样!

标签: java arrays class


【解决方案1】:
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();

playboard在哪里定义?

还有……这么多课程!改用 Main 类中的方法,它会让你的工作更轻松。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 2013-04-12
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多