在我的程序中添加循环(JAVA Netbeans)

时间:2016-11-30 16:15:34

标签: java netbeans

我需要一个循环来执行程序,通过说“y”并通过说“n”来结束它我只是不知道“while”循环应包含在其中的内容。我试过把“while(”y“.equals(answer))”并插入字符串,但我还在苦苦挣扎。

public class DiceRoller {

public static void main(String[] args) {
    DecimalFormat df = new DecimalFormat("#.#");
    Scanner sc = new Scanner(System.in);
    System.out.println("Welcome to the Dice Roller! "
            + "Do you want to roll the dice? (y: yes / n: to quit)");

    System.out.println("How many times would you like to roll the dice?");
    int rolls = sc.nextInt();
    int[] counts = new int[rolls];
    sc.close();
    for (int i = 0; i < counts.length; i++) {
        counts[i] = diceRoll();
    }//for
    int[] results = counters(counts);

    System.out.println("Roll\t\tCount\t\tPercentage");
    for (int i = 0; i < results.length; i++) {
        System.out.println((i + 2) + "\t\t"
                + (results[i])
                + "\t\t"
                + df.format(100.0 * (results[i])
                        / counts.length)
                + "%");
    }//for
}//main

public static int diceRoll() {
    Random rand = new Random();
    int dice1 = rand.nextInt(6) + 1;
    int dice2 = rand.nextInt(6) + 1;
    int roll = dice1 + dice2;
    return roll;
}//diceRoll

public static int[] counters(int[] arr) {
    int c1 = 0;
    int c2 = 0;
    int c3 = 0;
    int c4 = 0;
    int c5 = 0;
    int c6 = 0;
    int c7 = 0;
    int c8 = 0;
    int c9 = 0;
    int c10 = 0;
    int c11 = 0;
    int c12 = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == 2) {
            c2++;
        } else if (arr[i] == 3) {
            c3++;
        } else if (arr[i] == 4) {
            c4++;
        } else if (arr[i] == 5) {
            c5++;
        } else if (arr[i] == 6) {
            c6++;
        } else if (arr[i] == 7) {
            c7++;
        } else if (arr[i] == 8) {
            c8++;
        } else if (arr[i] == 9) {
            c9++;
        } else if (arr[i] == 10) {
            c10++;
        } else if (arr[i] == 11) {
            c11++;
        } else if (arr[i] == 12) {
            c12++;
        }
    }//for
    int[] rollCounts = new int[]{c2,
        c3,
        c4,
        c5,
        c6,
        c7,
        c8,
        c9,
        c10,
        c11,
        c12};
    return rollCounts;
}//counters
}//class Dice

1 个答案:

答案 0 :(得分:0)

这样做的一种方法是:

boolean ynprogram = false;
    Scanner sc = new Scanner(System.in);

    while(!ynprogram){
        System.out.println("Enter [Y/N]");
        String yn=sc.next();

        if(yn.equals("y") ||yn.equals("Y")){
            // Enter your code if the user inputed y N
            ynprogram = true;
        } else if(yn.equals("n") || yn.equals("N")){
            // Enter your code if the user inputed n N
            ynprogram = false;
        }

    }

希望这能帮到你得到你想要的东西:)。