【发布时间】:2017-03-05 16:55:37
【问题描述】:
我有这个脚本可以在 java 中模拟 2 个掷骰子。这会完成两次,一次由用户完成,一次由计算机完成(均自动完成)。程序输出卷并总结它们。但是,我无法使用 if/else 语句来比较掷骰结果并确定获胜者/或平局。到目前为止,我有:
import java.util.Scanner;
import java.util.Random;
import java.text.DecimalFormat;
/*
Program to simulate die roll
*/
public class Dice
{
Scanner scan = new Scanner (System.in);
Random generator= new Random();
int roll1;
int roll2;
int roll3;
int roll4;
int addroll1;
int addroll2;
public void userdieroll() // Simulates users role
{
roll1 = (generator.nextInt(7) +1); // Generate number from 1-6
System.out.println("Your first roll is "+roll1+"");// Says users first role
roll2 = (generator.nextInt(7) +1); // Generate number from 1-6
System.out.println("Your second roll is "+roll2+"");// Says users second roll
addroll1= roll1 +roll2;// Sums users roles
System.out.println("The sum of your two roles is "+addroll1+" \n");
}
public void compdieroll()// Simulates computers role
{
roll3 = (generator.nextInt(7) +1); // Generate number from 1-6
System.out.println("The computers first role is "+roll3+""); // Says computers first role
roll4 = (generator.nextInt(7) +1); // Generate number from 1-6
System.out.println("The computers second role is "+roll4+""); // Says computers second role
addroll2= roll3 +roll4;// Sums computers roles
System.out.println("The sum of the computers roles is "+addroll2+"");
}
public void findwinner()
{
if (addroll1 == addroll2)
{
System.out.println("Its a tie!");
}
else
{
if (addroll1 > addroll2)
{
System.out.println("You Won!");
}
else
{
System.out.println("You lost!");
}
}
}
public static void main(String[] args)
{
Dice userroll = new Dice();
userroll.userdieroll();
Dice comproll = new Dice();
comproll.compdieroll();
Dice looper = new Dice();
looper.findwinner();
}
}
【问题讨论】:
-
roll1 = (generator.nextInt(7) +1); // Generate number from 1-6,嗯,没有。生成一个从 0 到 6 的数字,然后加一个,将得到数字 1 到 7(含)。 -
是啊哎呀我的不好的好收获
标签: java if-statement int