我刚刚启动了java,所以这可能非常简单,但是我的班级中有4个人无法弄清楚这段代码有什么问题。我担心它可能是扫描仪和随机命令之间的重叠问题,因为.nextInt()是用于获取新输入并在0和n之间创建随机变量的命令。此外,我相当新的Stackoverflow所以如果有任何程序即将打破我应该尝试在将来适应,id很乐意接受你的建议。
感谢您提前帮助...干杯
import java.util.Scanner;
import java.util.Random;
public class Question4 {
public static void main(String arg[]){
//-----------------------------
int numdice;
int sides;
int count = 1;
int score;
int total = 0;
boolean loop = false;
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.print("Enter how many dice you would like to roll:");
numdice = scan.nextInt();
System.out.println("Enter how many sides to the dice there will be:");
sides = scan.nextInt();
System.out.println("You have rolled " + numdice + " dice with " + sides + " sides and have received the following values for each roll:");
while (!loop) {
if (numdice <= count){
score = random.nextInt(sides -1 ) +1;
total += score;
System.out.print(score);
++count;
}
else
{
System.out.println();
System.out.print(" your total value for your dices rolls are " + total);
loop = true;
}
}
System.out.println();
//-----------------------------
}
}
编辑:症状是程序运行但不创建/打印随机变量的任何值。该程序将打印else语句,但它声称总值= 0.根据Eclipse,程序中没有错误或错误。还要感谢你关于空格的说明。
你们是对的,照顾它。多么愚蠢涂料。谢谢seth和paku!我会评价你,但它不会让我。无论如何都要度过美好的一天!
答案 0 :(得分:1)
你的if语句是倒退的。 if (count <= numdice)
import java.util.Scanner;
import java.util.Random;
public class Question4 {
public static void main(String arg[]){
//-----------------------------
int numdice;
int sides;
int count = 1;
int score;
int total = 0;
boolean loop = false;
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.print("Enter how many dice you would like to roll:");
numdice = scan.nextInt();
System.out.println("Enter how many sides to the dice there will be:");
sides = scan.nextInt();
System.out.println("You have rolled " + numdice + " dice with " + sides + " sides and have received the following values for each roll:");
while (!loop) {
if (count <= numdice){
score = random.nextInt(sides -1 ) +1;
total += score;
System.out.print(score + " "); //Also, easier to read with a space.
++count;
}
else
{
System.out.println("Your total value for your dices rolls are " + total);
loop = true;
}
}
System.out.println();
//-----------------------------
}
}
答案 1 :(得分:0)
使用扫描程序和随机对象中的nextInt()
时应该没有问题。这些方法属于两个完全不同的类。
我认为你的while循环中的if语句有点倒退。你想掷骰子数量,是吗?因为现在你正在测试numdice是否小于你的掷骰数。这是你想要的吗?
if (count <= numdice){
答案 2 :(得分:0)
将if(numdice&lt; = count)改为if(numdice&gt; = count),你会得到答案......