java - 因未知原因而出现错误

标签 java arrays input coin-flipping

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

  }

}

最佳答案

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

应该是

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

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

关于java - 因未知原因而出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21393199/

相关文章:

java - 未生成新随机数

java - 为什么我们使用标志来停止线程?

c - 如何更改索引为空的数组值的索引

python - 使用 Python 比较两个文件夹(如 Linux 中的 diff 工具)

arrays - 比较两个数组并获取不常见的值

python - Input() 阻止 IDE 停止程序

jquery - 将 Checkbox 变成图标 IE9+

Java TCP 获取域名?

javascript - HTML 选择和文本输入

java - 找不到类(class)