我如何问用户是否希望使用netbeans在Java中进行每个骰子掷骰后继续游戏

我如何问用户是否希望使用netbeans在Java中进行每个骰子掷骰后继续游戏,第1张

我如何问用户是否希望使用netbeans在Java中进行每个骰子掷骰后继续游戏

扫描仪可用于提示用户询问他/她是否要继续。

您甚至可以跟踪编号。掷骰子的次数。

import java.util.Scanner;public class DiceGame {    public static int attempt = 1;        public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        int dice1 = (int) (Math.random() * 6 + 1);        int dice2 = (int) (Math.random() * 6 + 1);        int sum = dice1 + dice2;        while (true) { System.out.println(); System.out.println("Rolling dice for " + attempt + " time!"); dice1 = (int) (Math.random() * 6 + 1); dice2 = (int) (Math.random() * 6 + 1); sum = dice1 + dice2; System.out.println("Roll: total = " + sum); if (sum == 2 || sum == 3 || sum == 12) {     System.out.println("Sorry with a " + sum + " you loose :(!");     System.out.println();     break; } else if (sum == 7 || sum == 11) {     System.out.println("With a " + sum + " you win :)!");     System.out.println();     break; } System.out.println(); System.out.println("Do you wish to continue? Press 'y' for YES or ANY key for EXIT"); if (!scanner.next().equalsIgnoreCase("y")) {     break; } attempt++;        }        System.out.println("Thanks for playing dice game, you rolled the dice " + attempt + " times!");    }}

EDIT:
如果要在总和为4 5 6 8 9 10时自动掷骰子,则不再需要Scanner,即用户输入是否继续。

这是相同的解决方案。

public class DiceGame {    public static int attempt = 1;    public static void main(String[] args) {        int dice1 = 0;        int dice2 = 0;        int sum = 0;        while (true) { System.out.println(); System.out.println("Rolling dice for " + attempt + " time!"); dice1 = (int) (Math.random() * 6 + 1); dice2 = (int) (Math.random() * 6 + 1); sum = dice1 + dice2; System.out.println("Roll: total = " + sum); if (sum == 2 || sum == 3 || sum == 12) {     System.out.println("Sorry with a " + sum + " you loose :(!");     System.out.println();     break; } else if (sum == 7 || sum == 11) {     System.out.println("With a " + sum + " you win :)!");     System.out.println();     break;     // this will roll the dices automatically     // when sum is 4, 5, 6, 8, 9 or 10 } else {     System.out.println();     System.out.println("With " + sum + " dices are rolled again automatically!!");     attempt++; }        }        System.out.println("Thanks for playing dice game, you rolled the dice " + attempt + " times!");    }}

样品运行

Rolling dice for 1 time!Roll: total = 4With a 4, dices are rolled again automatically!!Rolling dice for 2 time!Roll: total = 6With a 6, dices are rolled again automatically!!Rolling dice for 3 time!Roll: total = 2Sorry with a 2 you loose :(!Thanks for playing dice game, you rolled the dice 3 times!


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5010870.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存