Search code examples
javaarraysinputcoin-flipping

Getting errors for unknown reason


Trying to design a coin flipper program that asks the user to state how many times they would like to flip a coin (# of flips must be under 1000). I then get a random number from 1-10 and assign that number to each array index declared based on the number of flips the user would lke.

I seem to be getting three errors involving the inability to resolve symbols on the math.random line. Any help would be appreciated.

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]);
        }
    }

  }

}

Solution

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

    should be

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

    flips[1000] is the 1001st slot, which is one too many.