所以我试图在我的主驱动程序类中创建的不同对象中获取多个用户输入,我似乎无法弄清楚如何执行此操作。网上的其他教程仅显示如何为一个对象执行此操作,但我有多个。
public class roulettedriver {
public static void main(String[] args) {
Scanner keyin = new Scanner(System.in);
// initializing the six players of the game
Player player1 = new Player(0, 0, 0, 0, 0);
Player player2 = new Player(0, 0, 0, 0, 0);
Player player3 = new Player(0, 0, 0, 0, 0);
Player player4 = new Player(0, 0, 0, 0, 0);
Player player5 = new Player(0, 0, 0, 0, 0);
Player player6 = new Player(0, 0, 0, 0, 0);
在我的其他班级玩家
public class Player {
int number1;
int number2;
int number3;
int number4;
int number5;
// constructor for each player at the table
public Player(int number1, int number2, int number3, int number4, int number5) {
this.number1 = number1;
this.number2 = number2;
this.number3 = number3;
this.number4 = number4;
this.number5 = number5;
所以我试图让keyin.nextInt()
的用户输入为每个玩家的number1,number2,number3,number4,number5,但我无法弄清楚如何做到这一点!
答案 0 :(得分:1)
在这种情况下,您将看到的标准“模式”之一是“工厂”。这本质上是一个专业类,唯一的工作就是制作另一个类的对象。在您的情况下,“工厂”将是PlayerFactory
,其方法可以使用Scanner
并从中创建Player
。它可以有几种方法来创建可用的球员。以下是一些示例代码,可帮助您入门:
class PlayerFactory {
public Player makeFromScanner(Scanner scannerIn) {
int number1 = scannerIn.nextInt();
int number2 = scannerIn.nextInt();
...
return new Player(number1, number2, ...);
}
public Player makeRandom() {
Random rand = new Random();
int number1 = rand.nextInt();
...
return new Player(number1, number2, ...);
}
}
然后您可以按如下方式使用它:
PlayerFactory factory = new PlayerFactory();
Player player1 = factory.makeFromScanner(scannerIn);
Player player2 = factory.makeRandom();
其他选项是使Player
构造函数成为其中一个:
class Player {
public Player(Scanner scannerIn) {
number1 = scannerIn.nextInt();
number2 = scannerIn.nextInt();
...
}
}
用作:
Player player1 = new Player(scannerIn);
或者您可以使构建方法成为Player
的静态方法:
class Player {
public static Player makeFromScanner(Scanner scannerIn) {
...
}
public static Player makeRandom() {
...
}
}
然后用作:
Player player1 = Player.makeFromScanner(scannerIn);
答案 1 :(得分:0)
可能是你试试这个:
public static void main(String[] s) throws NoSuchFieldException, SecurityException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
String numbers = null;
while(true){
System.out.println("Enter a five numbers (only numbers) or type kill, plis:");
numbers = br.readLine();//read a console value typed for user
if(numbers!=null && numbers.equals("kill")){//verify to continue running or exit
System.out.println("Exit");
break;
}
int[] numbersToParam = new int[5]; //array for the five parameters to your Player object
for(int i=0; i<numbers.length(); i++){
numbersToParam[i] = Integer.parseInt(numbers.substring(i, i+1));//parse 5 values to array
}
//create a new playes with parameters
new Player(numbersToParam[0],numbersToParam[1],numbersToParam[2],numbersToParam[3],numbersToParam[4]);
}
}
catch (IOException io)
{
System.err.println(io.toString());
}
}