Domanda

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

  }

}
È stato utile?

Soluzione

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.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top