【发布时间】:2021-05-18 02:49:34
【问题描述】:
我无法跟踪随机数生成器分配的变量。我正在尝试生成两个具有不同范围的随机数,并根据生成的数字更新分数或不更新分数,然后根据一组规则告诉用户他们是赢还是输。
我已经附上了下面的代码,所以你可以看到我在说什么,但我基本上需要关于变量 roll1 和 roll2 的帮助,谢谢你的帮助。
import java.util.Random; // import random number class
import java.util.Scanner; // Import the Scanner class
public class Main
{
public static void main(String[] args) {
//rules and variables
System.out.println("Welcome to lucky dice, the computer will roll 2 dice...");
//int roller1 = (int )(Math.random() * 10 + 1); //instance of random class
//int roller2 = (int )(Math.random() * 20 + 2); //instance of random class
//Random rand = new Random();
int total = 0;
int num = 0;
int max = 11;
int min = 1;
int max2 = 21;
int min2 = 2;
//create a loop to keep rolling until the user wins or looses
while (num <= 20 && total >= -50 && total < 150){
System.out.println("Are you ready to roll?");
Scanner reply = new Scanner(System.in); // Create a Scanner object
String answer = reply.nextLine();
Random rand = new Random();
if (answer == "yes"){
int roll1 = rand.nextInt(max - min) + min;//instance of random clas
int roll2 = rand.nextInt(max2 - min2) + min2;//instance of random clas
}while(roll2 % 2 == 1){
int roll2 = rand.nextInt(max2 - min2); //instance of random clas
}if (roll1 > roll2 || roll2 > roll1){
total = total + roll1 + roll2; //keep track of score and tell user
System.out.printf("Your roll was: " + roll1, roll2 + ".");
System.out.printf("Your score is now " + total + ".");
num = num + 1;
}else if (roll1 == roll2){
total = total + roll1 + roll2; //keep track of score and tell user
System.out.printf("Your roll was: " + roll1, roll2 + ".");
System.out.printf(" Your score is now " + total + ". ");
num = num + 1;
}
}if (num > 20){
System.out.println("You lost!");
}else if (total >= 150){
System.out.println("You won!");
}else if (total >= -50){
System.out.println("You lost!");
}
}
}
【问题讨论】:
-
“继续跟踪变量”是什么意思?我的意思是,你想要跟踪什么?
-
answer == "yes"不!这不是在 Java 中比较字符串的方法。 -
这个程序有什么例外?请编辑您的问题以包含完整的堆栈跟踪。
标签: java if-statement variables