Java硬币翻转用户输入的变量
我想创建一个Java程序,它接受用户输入的号码,然后翻转多次硬币,然后显示有多少头或尾部翻转到目前为止。 我的问题来了,当我不知道如何让程序翻转硬币次数的用户说,任何帮助?Java硬币翻转用户输入的变量
package E1;
import java.util.Scanner;
public class E1 {
public static void main(String[] args) {
int hCount = 0;
int tCount = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many coins should be tossed?");
input.nextInt();
if (Math.random() < 0.5) {
System.out.println("Heads");
hCount++;
} else {
System.out.println("Tails");
tCount++;
}
}
}
您可以创建一个对话框窗口,用户指示的次数,那么你就可以解决的是,看:
package E1;
import java.util.Scanner;
import javax.swing.*; // shows the dialogs windows
public class E1 {
public static void main(String[] args){
// This Dialog Window will ask the User how many times the coin will be tossed
int n_of_flips = JOptionPane.showInputDialog(null,
"Please indicate how many times you wish to flip the coin",
"Coin Flip",
JOptionPane.QUESTION_MESSAGE);
// the while loop
int x = 0;
while(x<= n_of_flips){
// your code here:
if (Math.random() < 0.5)
{
System.out.println("Heads");
x++;
}else{
System.out.println("Tails");
x++;
} // END while loop
} // END public static void
} // END of E1
欲了解更多信息,谷歌“的JOptionPane的Java”,你也可以在对话窗口中显示你的结果。玩得开心:
如果你喜欢答案,你可以投票,让我知道它是否工作:) –
对话框?为什么? –
这是一个选项,它是创建图形用户界面的一种方法。制作图形用户界面很有趣,Java有很好的工具 –
我建议以小写形式设置包名,因为它是一个广泛和良好的做法。
看看这个,它可能是你想要什么:
package e1;
import java.util.Scanner;
public class E1 {
public static void main(String[] args) {
int hCount = 0;
int tCount = 0;
Scanner input = new Scanner(System.in);
System.out.print("How many coins should be tossed? ");
int coinsCount = input.nextInt();
for (int i=0; i < coinsCount; i++) {
if (Math.random() < 0.5) {
System.out.println("Heads");
hCount++;
} else {
System.out.println("Tails");
tCount++;
}
}
System.out.println("Heads: "+hCount+", Tails: "+tCount);
}
}
下打破你的问题分解成更小的步骤。首先,你永远捕捉输入。其次,你知道如何编写一个正则循环吗? –
请参阅:[为什么“有人可以帮助我?”不是一个实际的问题?](http://meta.stackoverflow.com/q/284236) – EJoshuaS
另外,正如@ cricket_007所示,代码的图像没有帮助。请将代码添加为文字。 – EJoshuaS