尝试设计一个硬币翻转程序,要求用户说明他们想要翻硬币的次数(翻转数量必须低于1000)。然后,我从1-10获得一个随机数,并将该数字分配给根据用户将要翻转的翻转数声明的每个数组索引。
我似乎得到了三个错误,涉及无法解析math.random行上的符号。任何帮助将不胜感激。
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;
System.out.println("How many times would you like to flip your coin?");
flips = Integer.parseInt(in.readLine());
if(flips <= 1000) {
System.out.println("You want to flip " + flips + " times");
anArray = new int[flips];
for(x = 0; x <= flips; x++) {
r = Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
}
}
}
}
答案 0 :(得分:5)
for(x = 0; x <= flips; x++)
应该是
for(x = 0; x < flips; x++)
flips[1000]
是第1001个广告位,太多了。
答案 1 :(得分:2)
2个问题:
Math#round
返回一个长的,所以需要投射结果:
for(x = 0; x < flips; x++) {
r = (int) (Math.round(Math.random()*9)+1);
anArray[x] = r;
System.out.println(anArray[x]);
}
顺便说一句:import java.util.*
Math
java.lang
不需要{{1}}