【发布时间】:2014-11-16 00:20:13
【问题描述】:
我被困在这个 while 循环问题上,如果有人能指出我哪里出错了,我会很高兴 :)
高尔夫游戏 编写一个使用 while 循环来玩骰子高尔夫游戏的程序。到洞的距离从 100m 开始。该人反复选择使用哪个俱乐部。每个不同的选择对应一个不同面的虚拟“骰子”来滚动——即给出一个随机数。如果他们选择 1 号球杆(推杆),他们会掷出一个 0-5 的数字,代表击球距离。如果他们选择俱乐部 2(用于投球),他们会掷出 0-30 的数字。如果他们选择 3 号球杆(铁杆),他们会掷出 0 到 150 之间的数字。每次掷完后,该数字会从到球洞的距离中减去(下一轮的负距离为正)。它们一直滚动,直到它们的距离恰好为 0。当它们滚动时,拍摄的数量就会被打印出来。
The following shows an example run of the program:
Distance to hole 100m. Which club (1-putting, 2-pitching or 3-iron) 3
You hit it...120m
Distance to hole 20m. Which club (1-putting, 2-pitching or 3-iron) 2
You hit it...16m
Distance to hole 4m. Which club (1-putting, 2-pitching or 3-iron) 1
You hit it...1m
Distance to hole 3m. Which club (1-putting, 2-pitching or 3-iron) 1
You hit it...3m
Congratulations. You took 4 shots.
我是 java 新手,以下是我设法完成的工作,但显示错误:while (input.equals !( "1" || "2" || "3") )。我不确定它是否正确完成并花费了很长时间,如果有人可以帮助解决问题,我会很高兴:) 非常感谢。
public static void dicegolfgame(String[] args)
{
String input = "";
int difference = 0;
int newdistance = 0;
int distance = 0;
int i = 0;
while (input.equals ( "1" || "2" || "3") )
{
Random roll2 = new Random();
distance = roll2.nextInt(100);
input = JOptionPane.showInputDialog ( "distance to hole " + distance + " Which club (1-putting), 2-(pitching) or 3-iron");
while (difference > 0 && difference < 0)
if (input.equals ("1"))
{
Random roll = new Random();
newdistance = roll.nextInt(5);
i = i+1;
JOptionPane.showMessageDialog(null, "you hit ..." + newdistance + "m");
difference = distance - newdistance;
}
else if (input.equals ("2"))
{
Random roll = new Random();
newdistance = roll.nextInt(30);
i = i+1;
JOptionPane.showMessageDialog(null, "you hit ..." + newdistance + "m");
difference = distance - newdistance;
}
else if (input.equals ("3"))
{
Random roll = new Random();
newdistance = roll.nextInt(150);
i = i+1;
JOptionPane.showMessageDialog(null, "you hit ..." + newdistance + "m");
difference = distance - newdistance;
}
if (difference == 0)
{
break;
JOptionPane.showMessageDialog(null, "Congratulations, you took" + i + "shots.");
}
【问题讨论】:
-
while (difference > 0 && difference
-
我不确定,因为我说我是新手,但是即使差异为负,问题也要求 while 循环继续进行,所以我认为差异应该保持 >0 和
标签: java while-loop