0

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

  }

}
Zack
  • 591
  • 1
  • 9
  • 22
  • 1
    Array of length 10 has highest index of 9. Be careful with the difference between ` – takendarkk Jan 27 '14 at 22:43
  • 1) If it is a coin flipper: why 1- 10 and not 1 or 0 (or 2) 2) Why use Math.round ()? If it is an Integer, it will automatically be cut off after the comma. – Marenthyu Jan 27 '14 at 22:45
  • @Marenthyu second portion of program requires finding which # is flipped the most, part of assignment – Zack Jan 27 '14 at 22:49
  • Well for me a coin can only be one side or another - if it is a dice with tem faces im fine with this expression :P – Marenthyu Jan 28 '14 at 21:30

2 Answers2

5

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.

z5h
  • 21,947
  • 8
  • 64
  • 119
2

2 issues:

  • Arrays are zero based so you need to stop at the upper array bound less 1
  • Math#round returns a long so needs to be cast

result:

for(x = 0; x < flips; x++) {
    r = (int) (Math.round(Math.random()*9)+1);
    anArray[x] = r;
    System.out.println(anArray[x]);
}

BTW: You don't need the import java.util.* as Math is in java.lang

Reimeus
  • 152,723
  • 12
  • 195
  • 261
  • Thanks, I tried this out but I'm still getting the cannot resolve symbol errors. I wasn't aware that math.round returns a long. – Zack Jan 27 '14 at 22:47
  • 2
    From the [chat discussion](http://chat.stackoverflow.com/rooms/46179/discussion-between-zack-and-marenthyu) you have your own custom `Math` class - removing that class will allow program to compile :) – Reimeus Jan 27 '14 at 23:11