0

尝试设计一个抛硬币程序,要求用户说明他们想抛硬币多少次(抛硬币次数必须低于 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]);
        }
    }

  }

}
4

2 回答 2

5

for(x = 0; x <= flips; x++)

应该

for(x = 0; x < flips; x++)

flips[1000]是第 1001 个插槽,太多了。

于 2014-01-27T22:42:13.830 回答
2

2个问题:

  • 数组是从零开始的,所以你需要停在数组上限小于 1
  • Math#round返回一个 long 所以需要强制转换

结果:

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.*原样Mathjava.lang

于 2014-01-27T22:46:02.393 回答