滚动的次数为3次

时间:2015-09-21 21:42:34

标签: java arrays loops

import java.util.Random;
public class RollingDice {

public static void main(String[] args){
        int numSides = 6;
        Random ranGen = new Random();
        for (int i =1; i <= 20; i++){
            if (ranGen.nextInt(numSides) == 3) {
                System.out.println("A 3 has been rolled!");
                }
        }}}

到目前为止这是我的代码。每次滚动数字3时,它都会打印消息。我是编码新手,所以请耐心等待。我接下来要做的是存储3次滚动的次数,这样当循环退出时,它显示在该过程中实际滚动的次数3的最终计数。这使得最终结果是一些数字,表示系统滚动数字3的次数。

谢谢! -Sail

4 个答案:

答案 0 :(得分:6)

定义一个计数。

int count = 0;

每次遇到3卷时增加count。在循环内部,如果你滚动3:

count = count + 1;

在循环外打印count

System.out.printf("A 3 was been rolled %d times.\n", count);

答案 1 :(得分:-1)

Random ranGen = new Random();
int numberOfThrees = 0;
for (int i =1; i <= 20; i++){
  if (ranGen.nextInt(numSides) == 3) {
    ++numberOfThrees;
  }
}
System.out.println(numberOfThrees);

答案 2 :(得分:-2)

像这样:

import java.util.Random;
public class RollingDice {

public static void main(String[] args){
    int numSides = 6;
    int threes = 0;
    Random ranGen = new Random();
    for (int i =1; i <= 20; i++) {
        if (ranGen.nextInt(numSides) == 3) {
            System.out.println("A 3 has been rolled!");
            threes++
        }
    }
    System.out.println("A 3 has been rolled " + threes + " times!");
}}

实际上,您正在录制的是已滚动的4个数,因为nextInt返回0到5之间的数字。

答案 3 :(得分:-2)

你可以简单地拥有一个计数器

import java.util.Random;
public class RollingDice {

public static void main(String[] args){
    int numSides = 6;
    int cnt = 0; // <-- Declare a counter 
    Random ranGen = new Random();
    for (int i =1; i <= 20; i++){
        if (ranGen.nextInt(numSides) == 3) {
            System.out.println("A 3 has been rolled!");
            cnt++; // <-- increment counter
        }
    }
    System.out.printf("A 3 has been rolled %d times!\n", cnt);
}