我试图让编译器将数组从其中一个类传递到主方法。我不知道为什么它不起作用,代码如下:
这是我的主要方法 -
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;
}
}
我知道我可以轻松地将所有内容放入一个类甚至一种方法中,但我要练习使用类和方法,因此我创建了很多类和方法。
最佳答案
您必须首先创建 Main
和 methods
的新实例,或者声明 createBoard()
和 input ()
静态方法。
这是代码片段:
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
。
关于java - 如何通过类和方法传递数组和 int ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36514011/