【发布时间】:2014-01-28 00:24:46
【问题描述】:
我正在处理一个掷硬币的任务,我的大部分任务都正常运行(尽管与我在这里看到的代码相比,它的方式不太优雅)。
我试图找到一种方法来告诉用户哪个数字出现在他们的翻转中最多,如果正面分配给偶数#s,而反面分配给奇数#s,哪个出现最多。我正在寻找实现这些功能的建议。
这是目前为止的代码:
import java.io.*;
import java.util.*;
public class coinFlip {
public static void main(String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int flips;
int anArray[];
int x;
int r;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
int counter10 = 0;
System.out.println("How many times would you like to flip your coin?");
flips = Integer.parseInt(in.readLine());
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
}
if(flips <= 1000) {
System.out.println("You want to flip " + flips + " times");
anArray = new int[flips];
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
if (anArray[x] == 1) {
counter1 += 1;
}
else if (anArray[x] == 2) {
counter2 += 1;
}
else if (anArray[x] == 3) {
counter3 += 1;
}
else if (anArray[x] == 4) {
counter4 += 1;
}
else if (anArray[x] == 5) {
counter5 += 1;
}
else if (anArray[x] == 6) {
counter6 += 1;
}
else if (anArray[x] == 7) {
counter7 += 1;
}
else if (anArray[x] == 8) {
counter8 += 1;
}
else if (anArray[x] == 9) {
counter9 += 1;
}
else if (anArray[x] == 10) {
counter10 += 1;
}
}
System.out.println("\n You rolled 1 " + counter1 + " times.");
System.out.println("You rolled 2 " + counter2 + " times.");
System.out.println("You rolled 3 " + counter3 + " times.");
System.out.println("You rolled 4 " + counter4 + " times.");
System.out.println("You rolled 5 " + counter5 + " times.");
System.out.println("You rolled 6 " + counter6 + " times.");
System.out.println("You rolled 7 " + counter7 + " times.");
System.out.println("You rolled 8 " + counter8 + " times.");
System.out.println("You rolled 9 " + counter9 + " times.");
System.out.println("You rolled 10 " + counter10 + " times.");
}
}
}
【问题讨论】:
-
您已经存储了所有计数器,因此只需找到具有最高值的那个。此外,您的计数器应该是 10 个整数的数组,而不是 10 个单独的整数。
-
Helloooooww 开关...
-
当你有像
x1、x2、..xN这样的变量并对它们执行“相同的操作”时,请使用集合(例如数组或ArrayList)并使用循环来代替。 (而且我不太确定anArray应该做什么......) -
注意这一行
if(flips <= 1000)表示用户可以输入一个负数。您还应该确保它 >0。 -
10 面硬币?翻转和滚动?...这种术语组合让我感到困惑...我是唯一的一个吗?是骰子还是硬币……你是掷还是掷……
标签: java arrays input coin-flipping