Results 1 to 3 of 3
  1. #1
    LennyKosmos is offline Member
    Join Date
    Sep 2010
    Posts
    28
    Rep Power
    0

    Default How to use arrays with Math.random

    Introduction: hi, im lenny from sweden and i've been studying java for almost 2 weeks! i'm wondering how i can assign values to an array, 0 = heads and 1=tails and use math.random to randomize the arrays to make it a 50-50% chance.



    public class Krona {

    private String heads, tails;
    private String throw[];



    public void throw(){

    throw= new String[1];

    throw[0]=heads;
    throw[1]=tails;


    int throwOne=(int)(throw.length*Math.random());
    System.out.println(throwOne);
    }


    public class blabla {

    public static void main (String [] args){

    Throw Random = new Throw();
    Random.throw();
    }
    }
    }

    ERROR:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at Krona.kasta(Krona.java:14)
    at mainkrona.main(mainkrona.java:7)


    i dont understand this error :/

    edit: turned out to be weird when i was about to translate my methods and variables from swedish to english but i hope u can understand it either way :S
    Last edited by LennyKosmos; 09-20-2010 at 05:40 PM.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,773
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by LennyKosmos View Post
    Java Code:
    		throw= new String[1];
    		
    		throw[0]=heads;
    		throw[1]=tails;
    You want two elements in your array, element #0 and element #1 so the array in the first line should be new String[2], hence the exception that was thrown.

    kind regards,

    Jos

  3. #3
    LennyKosmos is offline Member
    Join Date
    Sep 2010
    Posts
    28
    Rep Power
    0

Similar Threads

  1. Math.random not zero
    By rsvr in forum New To Java
    Replies: 3
    Last Post: 02-28-2010, 02:57 AM
  2. Math.random
    By p0rnstar in forum New To Java
    Replies: 9
    Last Post: 01-27-2010, 02:26 AM
  3. Math.random()
    By Dieter in forum New To Java
    Replies: 4
    Last Post: 09-14-2009, 10:28 AM
  4. Math.Random
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-23-2007, 03:09 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •