如何编辑我的代码以包含方法,将其命名为rollDice(),以返回1到6之间生成的随机整数?感谢。
这是我目前的代码:
public class CrapsGame {
public static void main(String[] args) {
int dice1 = (int)(Math.random()* 6) + 1;
int dice2 = (int)(Math.random()* 6) + 1;
int roll = dice1 + dice2;
System.out.println();
System.out.print("You rolled "+roll+". ");
if(roll == 2 || roll == 3 || roll == 12){
System.out.println("You lose");
}
else if(roll == 7 || roll == 11){
System.out.println("You win");
}
else{
System.out.println("point is "+roll+"\n");
dice1 = (int)(Math.random()* 6) + 1;
dice2 = (int)(Math.random()* 6) + 1;
int roll2 = dice1 + dice2;
System.out.print("You rolled "+roll2+". ");
while(roll2 != 7){
if(roll == roll2){
System.out.println("You win");
break;
}
else{
System.out.println("point is "+roll+"\n");
}
dice1 = (int)(Math.random()* 6) + 1;
dice2 = (int)(Math.random()* 6) + 1;
roll2 = dice1 + dice2;
System.out.print("You rolled "+roll2+". ");
}
if(roll2 == 7){
System.out.println("You lose");
}
}
}
}
答案 0 :(得分:1)
public class CrapsGame {
public static void main(String[] args) {
int dice1 = rollDice();
(...)
}
private static int rollDice() {
return (int)(Math.random()* 6) + 1;
}
}