【发布时间】:2016-05-19 22:41:42
【问题描述】:
我正在为 Java 编写一个掷骰子程序。我不知道如何将扫描器“playerName”从主要方法传递到 playgame 方法和 rolldice 方法。我希望能够让程序在这两种方法中打印玩家姓名。 (例如“Jake 掷出 4 和 5 共 9”而不是“玩家掷出 4 和 5 共 9”。我还收到警告 Resouce Leak: 'sc' is never closed。我是新手编程场景,所以如果你能用简单的术语解释一下,我将不胜感激。也欢迎任何改进程序的建议。
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;
}
}
【问题讨论】:
标签: java variables methods scope java.util.scanner