我正在爲Java編寫Craps dice程序。我無法弄清楚如何將主要方法中的Scanner「playerName」傳遞給playgame方法和rolldice方法。我希望能夠用這兩種方法讓程序打印出玩家的名字。 (例如「傑克總共9次擲出4和5」,而不是「玩家擲出4和5,總共9次」我還得到警告Resouce Leak:'sc'永遠不會關閉。編程場景,所以如果你能深入淺出的講解,我將不勝感激。任何建議,以改善方案,也歡迎。將來自掃描器的輸入傳遞給方法
import java.util.Scanner;
import java.util.Random;
public class crapsgame
{
//generates random number to be used in method rollDice
private Random randomNumbers = new Random();
//enumeration of constants that represent game status
private enum Status {WIN, LOSE, CONTINUE};
//represents possible outcomes of rolling the dice
private final static int two = 2;
private final static int three = 3;
private final static int seven = 7;
private final static int eleven = 11;
private final static int twelve = 12;
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter a player name: ");
String playerName = sc.nextLine();
crapsgame game = new crapsgame(); //created object of class "crapsgame"
game.playgame(); //tells crapsgame object "game" to invoke"playgame" method
}
//method to play game
public void playgame()
{
int currentPoint = 0; //holds point value for current roll
Status gameResult; //contains one of enumeration values
int sumofDice = rollDice(); //sum after first roll
//determines if won, lost, or continue
switch (sumofDice)
{
case seven:
case eleven:
gameResult = Status.WIN;
break;
case two:
case three:
case twelve:
gameResult = Status.LOSE;
break;
//game continues if above conditions are not met
default:
gameResult = Status.CONTINUE;
currentPoint = sumofDice;
System.out.printf("Point is %d\n", currentPoint);
}
while (gameResult == Status.CONTINUE)
{
sumofDice = rollDice();
if (sumofDice == currentPoint)
gameResult = Status.WIN;
else
if (sumofDice == seven)
gameResult = Status.LOSE;
}
if (gameResult == Status.WIN)
System.out.println("Player wins");
else
System.out.println ("Player loses");
}
public int rollDice()
{
//choose a random number from 1-6
int firstroll = 1 + randomNumbers.nextInt(6);
int secondroll = 1 + randomNumbers.nextInt(6);
int sum = firstroll + secondroll;
System.out.printf("Player rolled %d and %d for a total of %d\n", firstroll, secondroll, sum);
return sum;
}
}