gpt4 book ai didi

java - 如何让我的扫描仪以多种方法工作

转载 作者:行者123 更新时间:2023-12-01 16:28:31 25 4
gpt4 key购买 nike

我正在为学校制作一款 Connect 4 游戏。我有一个玩家类,定义每个玩家的各个方面,棋盘类,“逻辑”类和运行游戏的游戏类。我的 Player 类有两个几乎相同的方法来设置每个玩家,唯一的区别是游戏 block ,X 或 O。Player 方法还读取注册 ID 和 gamerTag。它在player1上完美运行,但我得到java.util.NoSuchElementException。实际上,当我尝试运行任何使用 in.next...(); 的方法时,我收到了此错误

玩家类方法

public void setPlayer1() {
Scanner in = new Scanner(System.in);
System.out.println("\nPlayer 1 please enter your Arena registration ID.");
this.setID(in.nextLong());
System.out.print("");
System.out.println("Player 1 please enter the name you would like to use.");
this.setTag(in.next());
System.out.print("");
System.out.print(gamerTag + " your game piece is \"X\".");
this.setPiece("X");
in.close();
}

public void setPlayer2() {
Scanner in = new Scanner(System.in);
System.out.println("\nPlayer 2 please enter your Arena registration ID.");
this.setID(in.nextLong());
System.out.print("");
System.out.println("Player 2 please enter the name you would like to use.");
this.setTag(in.next());
System.out.print("");
System.out.print(gamerTag + " your game piece is \"O\".");
this.setPiece("O");
in.close();}

public static void main(String[] args) {
Connect4TextConsole game = new Connect4TextConsole();
System.out.print(board);
player1.setPlayer1();
player2.setPlayer2();
winner = Connect4.checkForWin(board);
while (!winner){
turn = turn.playerTurn(player1, player2);// switch players
int column = Connect4.askForColumn(turn);

}
}

最佳答案

您只需将其作为参数传递给方法

public void setPlayer1(Scanner in) {

System.out.println("\nPlayer 1 please enter your Arena registration ID.");
this.setID(in.nextLong());
System.out.print("");
System.out.println("Player 1 please enter the name you would like to use.");
this.setTag(in.next());
System.out.print("");
System.out.print(gamerTag + " your game piece is \"X\".");
this.setPiece("X");

}

public void setPlayer2(Scanner in) {

System.out.println("\nPlayer 2 please enter your Arena registration ID.");
this.setID(in.nextLong());
System.out.print("");
System.out.println("Player 2 please enter the name you would like to use.");
this.setTag(in.next());
System.out.print("");
System.out.print(gamerTag + " your game piece is \"O\".");
this.setPiece("O");
}

`public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Connect4TextConsole game = new Connect4TextConsole();
System.out.print(board);
//Here u give the scanner ur methods
player1.setPlayer1(in);
player2.setPlayer2(in);
in.close();
winner = Connect4.checkForWin(board);
while (!winner){
turn = turn.playerTurn(player1, player2);// switch players
int column = Connect4.askForColumn(turn);

}
}`

关于java - 如何让我的扫描仪以多种方法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62106798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com