gpt4 book ai didi

java - 如何将随机数添加到 java(blackjack) 的总数中?

转载 作者:行者123 更新时间:2023-11-30 03:04:37 24 4
gpt4 key购买 nike

这是我的代码:

import java.util.*;
import java.util.Scanner;

public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);

Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';

System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);

while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);


System.out.println("Card: "+ (random.nextInt(10)));
total = total + (random.nextInt(10));
System.out.println("Total: "+ total);


}

}
}

当我输入n时,如何才能让程序退出,而不是再次打印出总数?

最佳答案

看看这个:

public class Assignment2 {
public static void main(String args[]){
int next = 0;
Scanner stdin = new Scanner(System.in);

Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';

System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);

while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);

next = random.nextInt(10);
System.out.println("Card: "+ next);
total = total + next;
System.out.println("Total: "+ total);


}
if (exit.equals('n'))
system.exit(0);

}
}
  • 现在,通过调用 system.exit(0) 输入 n 后,程序就存在了.
  • 您只需调用 nextInt 一次,这样就不会创建 2 个不同的随机数。因此,我将第一个调用放入变量 next 中,以便您可以随意使用它,而无需再次调用 nextInt
  • 如果您希望程序在用户输入 n立即退出,您需要将 if 语句放在 exit = stdin.next().charAt(0);

关于java - 如何将随机数添加到 java(blackjack) 的总数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35105522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com