【发布时间】:2019-03-07 00:16:38
【问题描述】:
我正在介绍 java 类,对于我的一项作业,我必须使用循环(for 或 while)来跟踪我自己和计算机之间的分数。
这是我教授的逐字说明:
编写一个执行此操作的程序:您(作为程序员)是经销商。 为自己选择一个随机数(0 - 100 之间)。要求用户输入一个随机数(0 - 100 之间),谁更接近 21,谁就赢得了比赛。
(第 2 部分)-循环(保持计数器)编写相同的程序并使其继续运行,以便它继续播放(发牌并说出谁获胜)直到用户输入 21,此时您打印出一些统计数据并说再见。例如,您的再见可能如下所示:
游戏轮数:5 经销商获胜:3 玩家获胜:2
5 比 2。
现在我已经编写了代码并玩了好几个小时,但无法让它在循环中工作。我试过while,do while,for。我在互联网上到处寻找类似的例子,但无论如何都无法在我的程序中使用循环。如果有人有任何建议,我一定会感谢您的反馈。
我的代码:
import java.util.*;
class asd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
System.out.println("computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("the winner is the user!" + input);
dealerscore++;
gamesplayed++;
} else {
System.out.println("the winner is the computer!" + r);
userscore++;
gamesplayed++;
}
if (input == c) {
System.out.println("thank you for playing. you won.");
}
if (r == c) {
System.out.println("Thank you for playing:" + userscore);
System.out.println(userscore);
}
if (input == 0) {
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
while (input != c && r != c)
gamesplayed++;
}
// TODO code application logic here
}
一切正常,但我无法让循环在这里的任何地方工作。
【问题讨论】:
-
您的
while循环只包含一行代码gamesplayed++;,因此它将永远循环变量增加。您需要更改循环以包含您的游戏逻辑。
标签: java loops for-loop while-loop