Random array help.....

hi i'm pretty new to java, but i've made an array containing 5 toppings (for a pizza program). I want it so that each time i press the run program, a random topping pops up. How would I do this with an array?
thanks!!!!!!!!

ok hehe
this is what i did....it doesn't work, but i'm hoping you gurus would tell me what I did wrong and how I would edit this:
import java.lang.*;
public class Pizza
     public static void main(String[] arg)
          String[] toppings =
               {"Pepperoni", "Pineapple", "Green Peppers", "Sausage", "Bacon"};
          Random r = new Random();
               int arrayIndex = (int)(Math.random()*5);
               System.out.println("topping is..." + toppings[random.intValue]);
}

Similar Messages

  • I am trying to create N random arrays of a given length help please!

    Hi,
    I was given this picture last week as a block diagram in order to create N arrays of a specified length M. The array is to have a floating point representation (i.e. the values that make up the array of numbers can be anything specified by myself.
    I attach the picture here and was wondering if someone could tell me what the block diagram object to the right of the random number block diagram object is and where I can find it in LabVIEW, also the block diagram object underneath "N random arrays".
    Thanks, This picture is from LabVIEW v.6.1, I am using LabVIEW v.7.1.
    Alan Homer
    Message Edited by alanhomer on 03-21-2006 03:28 AM
    Attachments:
    N random arrays.png ‏5 KB

    Hi Alan,
    The function you want is a bundle found on the cluster palette. You need to make the bundle smaller as it comes off the palette with 2 input.
    I attach a VI that is a match to the image you sent, this contians everything wired together and should work out of the box.
    Regards
    JamesC
    NIUK and Ireland
    Attachments:
    alanhomer.vi ‏20 KB

  • A torrent i recently downloaded keeps popping up again and again and again. I've already downloaded it, but the download window still pops up randomly. Help!!!

    A torrent i recently downloaded keeps popping up again and again and again. I've already downloaded it, but the download window still pops up randomly. Help!!!

    Try to clear your download history. You will find help in [[Clear Recent History]].

  • Random Array Project Help.

    Hello, I'm new to this forum and to Java programming, I'm just looking for a little help on a project to see how random the Java random generator really is.
    I'm trying to produce 1000 random integers between 0 and 50 in an array.
    Then display how any times each number comes up.
    This is what i have so far and I'm really stuck.
    I have started with a smaller size array just to get it set up.
    import java.util.Random;
    public class randomArray
        public static void main (String[]args)
            Random gen = new Random();
            int[] ary = new int[10];
            for (int count=0; count<10; count++)
                ary[count] = gen.nextInt(51);
            for (int num=0; num<10; num++)
                System.out.println("ary[" +num+ "]= " +ary[num]);
    }What I need help with is how to display the occurrence of each number in the array....obviously
    with 10 integers its not likely that two of the same will show, but with a thousand I'm hoping it will
    work fairly well. Any help will be appreciated. thx

    import java.util.*;
    public class RandomTester{
    public static void main(String[] args){
         new RandomTester().start();
    public void start(){
         random = new Random();
         count = new int[50];
         for(int i = 0; i < 1000; i++){
         count[random.nextInt(50)]++;
         for(int i = 0; i < 50; i++){
         System.out.println("" + (i) + ": " + count);
         Random random;
         int[] count;

  • Array of unique random numbers - help?

    basically, i'm trying to create a BINGO card.
    i stared learning Java a week ago and am finding it easy to learn and use....at least so far.
    my instructor gave me the assignment to created a BINGO card. so i used the system.out.format command to make 5 tab fields, 8 spaces each ("%8s %8s %8s %8s %8s", "B", "I", "N", "G", "O"). although the assignment only wanted me to think numbers out of thin air, just to use as examples, i went above and beyond with the idea to make a BINGO card generator that could actually function.
    then i started the random number sequences, using the Math.random() command. all told, there are 24 of these in the program, one for each number on a bingo card. the field in the middle is the FREE space, so it has no Math.random command.
    in BINGO, each letter (one of my five tab fields) can have a number in ranges of 15. B is 1 to 15, I is 16 to 30, etc. it looks similar to this:
    B I N G O
    9 19 39 57 66
    3 28 32 51 74
    3 29 FREE 46 70
    14 28 43 55 67
    9 24 35 59 62
    as you can tell, i'm having trouble with actually making unique random numbers so that none repeat.
    is there a command or string or something to help me accomplish this?

    The best way I've come up with is to use an object to store the numbers that implements Collection--like ArrayList...
    Then you load it with the range of numbers that you want and call, shuffle() on the object, that will randomize your range of numbers and then you can choose the quantity you want from the storage object. So let's say you need 25 number in the range of 1 to 100:
    Add the numbers (you have to use classes so I would do Integers) 1 to 100;
    call shuffle()
    pull back the first 25 numbers
    This will guarantee that each number is distinct and in a random order.
    If you need multiple sheets populated, you can just call shuffle() between population of each sheet.
    package Junk;
    import java.util.ArrayList;
    import java.util.Collections;
    class Junk{
      private ArrayList<Integer> l;
      Junk(){
        l = new ArrayList<Integer>();
      public void loadList(int s, int e){
        for(int i=s; i<=e; i++){
          l.add(new Integer(i));
      public void randomizeList(){
        Collections.shuffle(l);
      public void printList5(){
        for(int i=0; i<5; i++){
          System.out.println(l.get(i));
      public static void main(String[] args){
        Junk j = new Junk();
        j.loadList(10,99);
        j.randomizeList();
        j.printList5();
        System.out.println();
        j.randomizeList();
        j.printList5();
    }

  • Problem: check random array with a static value

    My goal is to use the random number generator to put numbers into randomArray, then do a linear search to try to find if the number 5 has been generatated. Next print out where in the array the value can be found. I have no compile errors but I have a logical or syntax problem, any help would be great.
    public class test {
         int j;
         int target = 5;
         public static void main(String [] args) {
              int i;
              int[] randomArray = new int[20];
              for(i=0; i<randomArray.length; i++) {
                   randomArray[i] = (int)(Math.floor(Math.random() * (10.0 - 0.0)) + 0.0);
              test n = new test();
              n.display();
         public int arraySearch(int[] randomArray, int target) {
              for (j=0; j<randomArray.length; j++) {
                   if (randomArray[j] == target) {
                        return j;
              return -1;
         public void setArraySearch(int j) {
              j = j;
         int p;
         public void setArrayValues(int[] randomArray) {
              for (int k=0; k<randomArray.length; k++) {
                   p = randomArray[k];
         public void display() {
              System.out.println("Five is found in array position " + j);
              System.out.println(p);
    }

    Hi,
    That's correct. You need to call the other methods just as you call display, but you do also have some other minor problems. You have written some methods that aren't needed, and they do nothing. This might help you:
    public class test {
         public static void main(String [] args) {
              int i;
              int[] randomArray = new int[20];
              for(i=0; i<randomArray.length; i++) {
                   randomArray[i] = (int)(Math.floor(Math.random() * (10.0 - 0.0)) + 0.0);
              test n = new test();
              int indexFound = n.arraySearch(randomArray, 5);                
              n.display(indexFound );
         public int arraySearch(int[] randomArray, int target) {
              for (j=0; j<randomArray.length; j++) {
                   if (randomArray[j] == target) {
                        return j;
              return -1;
         public void display(int indexFound) {
              System.out.println("Five is found in array position " + indexFound);
    } /Kaj

  • Gahering Data for Random Array

    I've searched the boards for help on this and doing so has
    taught me SOME of what I need to do, but not all.
    I think I can construct an array now, but what I need to know
    how to do is GATHER the data for the array from user-inputted text,
    then have Flash return a # of those inputs at random.
    It's for drug screening. I need to be able to input Employee
    names (collected by the array) and then enter the # of employees I
    want to have tested (say 6 out of 20 names entered). Then I want
    Flash to give me 6 of those names at random without duplicating.
    Like I said, from searching here, I think I learned how to
    build the array using the dynamic text boxes. What I haven't seen
    is how to return X # of that data to the user at random.
    Any ideas?

    Once you have an array, you can shuffle it and then just
    count off however many elements you need.
    http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=15&catid=288&threadid =1170742&highlight_key=y&keyword1=shuffle
    Obviously I am partial to the one that I have posted about
    halfway down. :)
    And it looks like blemmo has improved it at the end of this
    thread.
    http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=15&catid=288&threadid =1039424&highlight_key=y&keyword1=shuffle
    But I would still recommend including the ASSetPropFlag line
    from my post.

  • Writing random array positions to file

    Hi all.
    I have an array of 1000 positions each consisting of a String.
    I want to write the strings equally to two seperate text files which i have managed without any probs.
    The problem is i want to write these strings in a total random order so each time its run different strings would end up in different files and in total different order.
    i know how to generate a random number but not sure how to access all positions of the array but in random order.
    Any help would be appreciated.
    thanks

    The Random class has methods that generate random ints.
    You can use those ints to index the array and get the String from that position.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html

  • Random array

    Hi,
    I have a tile based maze game that i want to be able to
    choose a level at random. The tiles are arranged by script using a
    2D array (the standard way to make tiles with script??), so for
    example one array is called gameOne = [array], gameTwo = [array]
    etc....
    Anyone have any ideas how to go about this?
    Any help would be much appreciated.

    Hi, sorry to be such a dummy....
    I have each one of my games in a seperate Array. Im not sure
    what part of the code i put in 'for' section of the code you
    suggested. I understand the rest of it but its just the last bit i
    dont understand.....I have attached my code to make myself clear.
    Thanks for you help....
    my Arrays look like this..

  • Mystery numbers game array help!

    Hey guys thanks for taking the time to help me out. Im trying to develop this GameBoard class for a game but im having trouble using a for loop to generate an array of random numbers heres my code:
    import java.util.*;
    * CSC15 Spring 2008 - Lab Assignment G         Matt Mattson
    *              GameBoard class  
    * This class provides the "Game board" for the Mystery Numbers Game.
    * It manages the mystery numbers to be guessed, process the guesses
    * the player makes and keeps a history of the guesses that have been
    * made.
    public class GameBoard
        private int boardSize;
        private int[] mysteryNumbers;
        private static Random randGenerator= new Random();
        private String guessHistory;
         * Constructor: initializes the size of the game board (how many
         *   numbers will be guessed), generates the mystery numbers to be
         *   guessed and initializes the history of the guesses made.
         * @param size is the number of numbers the player will be required
         *   to guess (a value in the range 3 to 5).
        protected GameBoard(int size)
            boardSize=size;
            mysteryNumbers= new int[boardSize];
            for(int i=0;i<boardSize;i++)
                int mysteryNumbers=randGenerator.nextInt(MysteryNumbersGame.BIGGEST_NUMBER)+1;
    }I get a '[' bracket error but im unfamiliar with this sysntax so can someone show me what im missing!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    You already told javac what type of variable mysteryNumbers is. No need to tell it again.
    for(int i=0;i<boardSize;i++)
                int mysteryNumbers=randGenerator.nextInt(MysteryNumbersGame.BIGGEST_NUMBER)+1;
    }should befor(int i=0;i<boardSize;i++)
    mysteryNumbers[i]=randGenerator.nextInt(MysteryNumbersGame.BIGGEST_NUMBER)+1;
    }Now you may have other problems too I don't know but that's your current issue.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problem Bubble sorting random array

    For my CompSci class I have to create an array with random number in it and then do a bubble sort. I was able to create the array and input the variables in it but when it bubble sorts the array none of the values in the sorted array correlate to the original integers in the array.
    Any help would be greatly appreciated.
    public class RandomSort {
    public static void main(String[] args) {
        final int ARRAY_SIZE = 20;
        final int RAND_MIN = 0;
        final int RAND_MAX = 100;
        int [] randomSort = new int [ARRAY_SIZE];
        int i;
        for (i = 0; i < randomSort.length; i++)
            randomSort[i] = (int) (Math.random()*(((RAND_MAX - RAND_MIN)+1)+RAND_MIN));
        for (i=0; i<ARRAY_SIZE; i++)
                for (int j = 0; j <=i-1; j++)
                        if (randomSort[j] > randomSort [j+1])
                            int temp = randomSort[j];
                            randomSort[j] = randomSort[j+1];
                            randomSort[j+1] = temp;
                System.out.println(randomSort);

    Mmmhhh....
    for (i = 0; i < ARRAY_SIZE; i++) {
         for (int j = ARRAY_SIZE - 1; j >= i + 1; j--) {
              if (randomSort[j - 1] > randomSort[j]) {
                   final int temp = randomSort[j - 1];
                   randomSort[j - 1] = randomSort[j];
                   randomSort[j] = temp;
         System.out.println(randomSort);
    Pffff....9
    31
    32
    33
    34
    36
    37
    39
    45
    63
    64
    81
    84
    85
    86
    91
    94
    94
    99
    100Aarrfff...  [http://en.wikipedia.org/wiki/Bubble_sort|http://en.wikipedia.org/wiki/Bubble_sort]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Loops and Arrays help

    Hi,
    I'm a freshman in college and new to java. I am completely lost and really need help with a current assignment. Here are the instructions given by my teacher...
    Building on provided code:
    Loops and Arrays
    Tracking Sales
    Files Main.java and Sales.java contain a Java application that prompts for and reads in the sales for each of 5 salespeople in a company. Files Main.java and Sales.java can be found here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Main.java
    and here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Sales.java It then prints out the id and amount of sales for each salesperson and the total sales. Study the code, then compile and run the program to see how it works. Now modify the program as follows:
    1. (1 pts) Compute and print the average sale. (You can compute this directly from the total; no new loop is necessary.)
    2. (2 pts) Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., "Salesperson 3 had the highest sale with $4500." Note that you don't necessarily need another loop for this; you can get it in the same loop where the values are read and the sum is computed.
    3. (2 pts) Do the same for the minimum sale.
    4. (6 pts) After the list, sum, average, max and min have been printed, ask the user to enter a value. Then print the id of each salesperson who exceeded that amount, and the amount of their sales. Also print the total number of salespeople whose sales exceeded the value entered.
    5. (2 pts) The salespeople are objecting to having an id of 0-no one wants that designation. Modify your program so that the ids run from 1-5 instead of 0-4. Do not modify the array-just make the information for salesperson 1 reside in array location 0, and so on.
    6. (8 pts) Instead of always reading in 5 sales amounts, allow the user to provide the number of sales people and then create an array that is just the right size. The program can then proceed as before. You should do this two ways:
    1. at the beginning ask the user (via a prompt) for the number of sales people and then create the new array
    2. you should also allow the user to input this as a program argument (which indicates a new Constructor and hence changes to both Main and Sales). You may want to see some notes.
    7. (4 pts) Create javadocs and an object model for the lab
    You should organize your code so that it is easily readable and provides appropriate methods for appropriate tasks. Generally, variables should have local (method) scope if not needed by multiple methods. If many methods need a variable, it should be an Instance Variable so you do not have to pass it around to methods.
    You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this.
    I'm not asking for someone to do this assignment for me...I'm just hoping there is someone out there patient and kind enough to maybe give me a step by step of what to do or how to get started, because I am completely lost from the beginning of #1 in the instructions.
    Any help would be much appreciated! Thank you!
    Message was edited by:
    Scott_010
    Message was edited by:
    Scott_010

    First ask the person who gave this asignment as to why do you require two classes for this , you can have only the Sales.java class with main method in it . Anyways.
    Let Main.java have a main method which instanciates a public class Sales and calls a method named say readVal() in Sales class.
    In the readVal method of sales class define two arrays i.e ids and sales. Start prompting the user for inputting the id and sales and with user inputting values keep storing it in the respective arrays .. Limit this reading to just 5 i.e only 5 salesPerson.
    Once both the arrays are populated, call another method of Sales class which will be used for all computations and output passing both the arrays.
    In this new method say Compute() , read values from array and keep calculating total,average and whatever you want by adding steps in just this loop. You can do this in readval method too after reading the values but lets keep the calculation part seperate from input.
    You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this. I think this is ur personal stuff , but if you want to use web page , you probably will require to use servlet to read values from the html form passed to the server.

  • Reading from a text file in to an array, help please

    I have the following
    public class date extends Loans{
    public int dd;
    public int mm;
    public int yyyy;
    public String toString() {
    return String.format( "%d,%d,%d", mm, dd, yyyy );
    public class Loans extends Borrowing {
    public String name;
    public String book;
    public date issue;
    public char type;
    public String toString(){
    return String.format( "%s, %s, %s, %s", name, book, issue, type );
    import java.util.Scanner;
    import java.io.*;
    public class Borrowing extends BorrowingList {
    private Loans[] Loaned = new Loans[20];
    if i want to read in from a text file in to that array how do i do it?

    sorry to keep bothering you and thanks loads for your help but now I am getting the following error mesage
    C:\Documents and Settings\MrW\Menu.java:43: cannot find symbol
    symbol : class IOException
    location: class Menu
    }catch(IOException e){
    Note: C:\Documents and Settings\MrW\Borrowing.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    1 error
    BUILD FAILED (total time: 0 seconds)
    for this line
    }catch(IOException e){                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Populating 1D Array, Help with 1 Error

    Hello,
    I have just about finished a program that implements a .txt file containing a few records. The order is an int customerNumber, string firstName, string lastName, and float balance. The snipplet of code posted below is where I believe the problem lies, I just cant figure out where it is. Im not sure if my counter is not working correctly or what. The problem is that I'll input the customer number of the first record and it will output fine, but when I type in any other customer number, it returns null. It is supposed to return null if the customer number is not found in the array. The snipplet of code is posted below and if needed, i will post the entire program. Thanks for any help and feel free to ask questions:
    import java.util.Scanner;
    import java.io.*;
    public class customerList {
         private int count;
         private customerRecord data[];
         public customerList()
         data=new customerRecord[100];
         count=0;
    public void getCustomerList(String fileName) throws IOException
         while(count<100)
         Scanner scan=new Scanner(new File("/Users/kd/Documents/workspace/Assignment1/src/records.txt"));
              int customerNumber=scan.nextInt();
              String firstName=scan.next();
              String lastName=scan.next();
              float balance=scan.nextFloat();
              data[count]=new customerRecord(customerNumber, firstName, lastName, balance);
              count++;
    public customerRecord getCustomer(int customerNumber)
              for(int i=0; i<data.length; i++)
                   if(data.getCustomerNumber()==customerNumber)
                        return data[i];
              return null;

    ahh, i see....stupid mistake. would it still be 'legal' for me to do:
    public void getCustomerList(String fileName) throws IOException
         Scanner scan=new Scanner(new File("/Users/kevindoster/Documents/workspace/Assignment1/src/records.txt"));
         while(count<100)
              int customerNumber=scan.nextInt();
              String firstName=scan.next();
              String lastName=scan.next();
              float balance=scan.nextFloat();
              data[count]=new customerRecord(customerNumber, firstName, lastName, balance);
              count++;
    }or is there a problem with my limitations in the while loop

  • New Builder needs some info K9A Plat. RAID Array help

    This is a new build AMD 64x2 6000+, K9A platinum, Lite On DVD Re Writeable SATA, 2x74Gig WD Raptors in Raid 0, Asus X1950 pro Thermaltake 700 W PSU Crossfire cert.
    BIOS registered my drives, Built array PC Rebooted, Installing Win XP pro Hit F6 install drivers, Format drives, Then before Install  It says that :setup cannot copy the file ahcix86.inf.
    If I skip it, it will install XP but when I try to boot from the hard drive It starts to load XP but crashes to the blue screen of death
    *** Stop: 0x0000007BC ( 0xF78A2524, 0xC0000034, 0x00000000, 0x00000000)
    Has anyone got this error string?
    First RAID array I would very much appreciate any help given.

    Hi!
    Looking at some info on Google and Microsoft site, I cannot find the BC error code, only the error code ending with B. It indicates an error with the boot device. It can be caused by several things.
    Check that you are using the correct device drivers to install Windows
    Also, check the installation CD. It could be that the disk was damaged and that you are missing a crucial file because of that
    You can also try installing Windows again and choose to recover the previous installation.
    If this all does not help, try installing Windows on a single HDD (no raid) to see if that will work.

Maybe you are looking for

  • Problem with Generics

    I have the following practice program:import java.util.*; public class ShowRoom     private List<Car> list;     public ShowRoom()         list = new ArrayList<Car>();     protected void putInRoom(Car car)         list.add(car);     protected void tak

  • Why No Picture When Full Screen Button Is Pressed?

    When I open up IPhoto all the thumbnails load OK. Yesterday I tried to show my grandson some of his younger pictures taken 3 years ago by hitting the Full Screen button. What we saw was a dotted frame with an exclamation mark inside. To my dismay man

  • HT5639 Are there inherent security risks for installing windows operating systems on a mac?

    Just wondering if I use "bootcamp" and install Windows operating system and find out one of the main reasons I switched to a Mac is because of security issues. I also need to know if I can operate the Mac version of "Microsoft Office" without install

  • Obiee 11g non-conforming dimension filters

    I have a non-conforming design configured in 11g that is functional. However, I have run into an issue where if I attempt to filter on columns from two non-conforming dimensions, I receive the following error. [nQSError: 14023] None of the fact sourc

  • My macbook 2007 won't start up past the logo screen.

    My macbook 2007 won't start up past the logo screen. I've tried to boot the computer off the install dvd that came with it but it comes up with a box saying that Mac OS X can't be installed on this computer. It has a yellow triangle over a hard drive