Polymorphism and Random Numbers

Im having issues correctly using random numbers in this program.All I want to do is: generate 4 random ints,and 3 random operators,then prints the results in a toString() method
import java.util.Random;
public class TestArithmetic2 {
    // evaluate (int / int) - (int * int)) = result
      //((8.0 / 8.0) - (2.0 * 5.0)) = -10.0
    public static void main(String[] args) {
        Node n = new RandomOps(
            new RandomOps(
            new RandomConst(), new RandomConst()),
            new RandomOps(new RandomConst(), new RandomConst()));
               public Character RandomOperator(){
                    Random random = new Random();
                    //char array with characters
                    char[] chars = new char[]{'+','-','*','/'};
                    //Generate a random number
                    int r = randomChar.nextInt(chars.length);
                    //Get char at random index
                    char randomOps = chars[r];
               public int RandomConstant(){
                    int randomConst = 1 + (int)(Math.random() * 20);
               public String toString(){
                    return "(" + "(" + lChild.eval() + "-" + rChild.eval() + ")" + ")" + "=" n.eval();
        System.out.println(""+ n.eval());
}

Opps.Sorry.Here's everything that should help it compile.
public class Node {
    public Node() {}
    public double eval() {
        System.out.println("Error: eval Node");
        return 0;
import java.util.Random;
public class TestArithmetic2 {
    // evaluate (int / int) - (int * int)) = result
      //((8.0 / 8.0) - (2.0 * 5.0)) = -10.0
    public static void main(String[] args) {
        Node n = new RandomOps(
            new RandomOps(
            new RandomConst(), new RandomConst()),
            new RandomOps(new RandomConst(), new RandomConst()));
               public Character RandomOperator(){
                    Random random = new Random();
                    //char array with characters
                    char[] chars = new char[]{'+','-','*','/'};
                    //Generate a random number
                    int r = randomChar.nextInt(chars.length);
                    //Get char at random index
                    char randomOps = chars[r];
               public int RandomConstant(){
                    int randomConst = 1 + (int)(Math.random() * 20);
               public String toString(){
                    return "(" + "(" + lChild.eval() + "-" + rChild.eval() + ")" + ")" + "=" n.eval();
        System.out.println(""+ n.eval());
public class Binop extends Node {
    protected Node lChild, rChild;
    public Binop(Node l, Node r) {
         lChild = l; rChild = r;
}

Similar Messages

  • Bips and random numbers while making calls

    When talking on the phone (iPhone 4 with iOS 6) I get beeping noises and random numbers generated at the top of the screen. Has anyone else encountered this? HELP!

    I'm having the same issue and it has just started after the recent OS update. I have a 5S. Hope there is a fix, as it is terribly annoying.

  • Image loading and random numbers?

    Hi. I'm programming a text-based RPG using Swing.
    But I have two things to hamper my progress:
    1) I can't create random numbers
    2)I can't put images onto my window.
    Can anyone tell me a method to use do do these two things? Thanks.

    Hi. I'm programming a text-based RPG using Swing.
    But I have two things to hamper my progress:
    1) I can't create random numbersSee java.util.Random
    2)I can't put images onto my window.See Graphics.drawImage
    >
    Can anyone tell me a method to use do do these two
    things? Thanks.

  • Getting odd symbols and random numbers

    When receiving texts both my and my wifes phone are getting randoms symbols and numbers instead of the text message.. We thought it may be just hers but now both are doing it

    What phones do you both have? It could be caused by someone sending you a message with an animation in it that your phone can't "translate".
    A signature can cause the text to be scrambled, and special characters or formatting can cause the same behavior in the received message.
    Also, see if the the texts being sent are longer than the standard 160 characters....then post back and let us know if any of these apply and make a difference when changed.

  • I am trying to generate an array of 30 random numbers. after every 5 readings a new vi should open and tell the user that 5 readings has been completed. and again carry on with the generation of array.

    since i do not have a transducer now, i am currently generating an array of 30 random numbers. after every 5 readings a warning should be given to the user that 5 readngs are complete. this cycle should repeat. the array size is 30.
    please help me out,  waiting for reply asap.
    once i have the transducer, i will be taking 30 analog samples and then after every 5 smaples that wraning will be displaye din a new VI
    Solved!
    Go to Solution.

    Use a while loop with a time delay representing your sampling period.
    Use the count terminal to check if equals 4, so 4th iteration=5th sample.
    Use a case structure. The true case will only be executed on the 4th iteration.
    In the true case place a subVI  with your desired message in the front panel. Go to the VI properties window and set "open front panel when called".
    The closing condition of the warnign is not giving in your description.
    Consider that rather than usign a subvi for this, you could use the "One/Two/Three button dialog" or "display message" vis at the "dialog and user interface" pallete.
    Please give it a try and send your own VI. Do not expect us to provide a working solution.
    Regards,

  • Can't validate outlook on iPad - random numbers and letters don't display - only a question mark in a blue box

    If I have to validate Outlook on PC or Mac - I have no problem - the random numbers and letters display fine - but if I am requested to validate outlook before sending a mail when using my iPad, the operation fails as the test numbers and letters are not shown - only a snap blue box with a question mark.  How do I convert the box into the image of a new validation code?  Thanks in advance.

    Hello,
    The question mark means it can't find it where it was when you put it in the Dock.
    I'd get EasyFind...
    http://www.macupdate.com/info.php/id/11076
    Use it to search your whole drive for Files & Folders, case insensitive & show invisibles...
    Complete
    That will show any with that word in the name at all.

  • How do you generate multiple random numbers between 1 and 49

    I am new at mac programming and I want to make an iPhone app with the free SDK. What I would like to try is a random number generator. I imagine it as when the user clicks a button 6 random numbers from 1 to 49 would appear in a label or another control. If someone could please give me the code that would place these randomized numbers in a label I would greatly appreciate it. I know how to link all the controls together, I just need the code. Thank-you to anyone that can help!

    semi-sudo code goes here
    --prepare and array which will have number from 0 to 49
    --loop thru the array like this
    int i=0
    for (i; i<=49; i++) {
    int a=arc4random() % 49] ;
    int b=arc4random() % 49];
    --here exchange the objects so that they are shuffled
    [myArray exchangeObjectAtIndex:a withObjectAtIndex:b];

  • Create Random Numbers using OLE Randomize and RND

    Hi,
    I've managed to create an excel spreadsheet by creating an object of type EXCEL.APPLICATION. I've also managed to rename the worksheet tabs, move from one tab to another as well as fill certain cells with numbers.
    I would now like to create a range of random numbers within one of these worksheets. I believe I should be using the Randomize and RND methods contained within the VBA OLE object. This is what I've done so far :
    DATA: gs_vba TYPE ole2_object,           "VBA object
               gs_math TYPE ole2_object.
    CREATE OBJECT gs_vba 'VBA'.
    CALL METHOD OF gs_vba 'MATH' = gs_math.
    CALL METHOD OF gs_math 'Randomize' = gs_math.
    CALL METHOD OF gs_math 'Rnd' = gs_math
      EXPORTING
        #1 = 1000.
    Is the above the right way to do it? If not, I would really appreciate your help, and if possible, some sample code to do this as well.
    Thanks and regards,
    Adeline.

    Hi,
    I've managed to create an excel spreadsheet by creating an object of type EXCEL.APPLICATION. I've also managed to rename the worksheet tabs, move from one tab to another as well as fill certain cells with numbers.
    I would now like to create a range of random numbers within one of these worksheets. I believe I should be using the Randomize and RND methods contained within the VBA OLE object. This is what I've done so far :
    DATA: gs_vba TYPE ole2_object,           "VBA object
               gs_math TYPE ole2_object.
    CREATE OBJECT gs_vba 'VBA'.
    CALL METHOD OF gs_vba 'MATH' = gs_math.
    CALL METHOD OF gs_math 'Randomize' = gs_math.
    CALL METHOD OF gs_math 'Rnd' = gs_math
      EXPORTING
        #1 = 1000.
    Is the above the right way to do it? If not, I would really appreciate your help, and if possible, some sample code to do this as well.
    Thanks and regards,
    Adeline.

  • Choosing serveral random and unique numbers

    Hi
    I'd like to select 9 random numbers out of a set of let's say
    1-20. They can't repeat and each has to be saved into a different
    variable P1-P9.
    Any ideas?
    Thanks

    Make an array of the numbers 1 through 20.
    Shuffle the array.
    Take off as many numbers as you need.
    Search the forums for shuffle to find out how to shuffle the
    array.

  • HT201317 I recent returned from an eight day trip during which I took over 100 photos.  When I returened home yesterday, I turned on my computer and Photostream downloaded about half (randomly numbered) of my photos. The rest have not downloaded after 36

    I recently returned from an eight day trip during which I took over 100 photos.  When I returned home yesterday, I turned on my computer and about half (randomly numbered) of my photos downloaded to Photo Stream.  I have been waiting for about 36 hours now and the rest have not downloaded.  What could be the problem?
    As additional infromation, I tried turning OFF Photo Stream on the I Cloud Control Panel and then back ON to no avail.  And all my previous pictures (taken on other trips) have downloaded completly with no problems.
    FVP36

    Have you checked your Photos application for Photostream? Photos are saved for 30 days in photo stream and can be moved to camera roll.
    Let me know if I can specify the search.
    SRO

  • Phone is malfunctioning, voice command comes on and calls random numbers or plays Ipod

    Phone is malfunctioning, voice command comes on and calls random numbers or plays Ipod

    Have you tried the standard fixes:
    - Reset
    Reset iPod touch:  Press and hold the On/Off Sleep/Wake button and the Home
    button at the same time for at least ten seconds, until the Apple logo appears.
    - Restoring from backup
    - Restoring to factory defaults/new iPod
    Are you using the headphone/mic?  If so sometimes sweat/moisture in the controls can make the iPod do strange things.
    What number are you looking for?
    If les than a year old, the Apple warranty still covers it.

  • My iPhone 5 types random letters and dials random numbers

    MY iPhone 5 types random letters and dials random numbers even when I am not holding the phone

    Hello diana239,
    If your iPhone is randomly accessing apps and dialing out, then take a look at the article below to troubleshoot issues with the display on your iPhone. 
    If the screen on your iPhone, iPad, or iPod touch doesn't respond to touch
    http://support.apple.com/en-us/HT201406
    Regards,
    -Norm G. 

  • Working with random numbers and probabilities

    Hi again,
    i am working with random numbers at the moment.
    in the first step i do create a random number between 3 and 8 which is stored to a variable.
    set myVAR1 to random number from 3 to 8 as integer
    Lets assume myVAR1 is 5
    Now i want to select 5 numbers out of number pool from 1 to 8. Each number should be pickable only once.
    How would i realize that ?
    I guess i need some kind of pool, array and then select 5 out of this array, but i am not sure about the syntax.
    In best case i would like to add probabilities to those 8 numbers in the pool.
    i.e.
    1 (5%),2(5%),3(20%),4(10%),5(20%),6(10%),7(15%),8(15%)
    any help is heavily appreciated
    best regards
    fidel

    Hello fidel,
    For selecting unique numbers from given pool, try something like this.
    --SCRIPT 1
    (* select unique numbers from pool *)
    set pool to {1, 2, 3, 4, 5, 6, 7, 8} -- number pool
    set n to random number from 3 to 8 -- selection count
    return {n, random(n, pool)}
    on random(n, pool)
    set kk to {}
    repeat with i from 1 to count pool
    set end of kk to i
    end repeat
    set rr to {}
    repeat n times
    set k to kk's some integer
    set kk's item k to false
    set end of rr to pool's item k
    end repeat
    return rr
    end random
    --END OF SCRIPT 1
    For introducing selection weight of each number in the pool, you may try the below.
    --SCRIPT 2
    (* select unique numbers from pool with stochastic weights *)
    set pool to {1, 2, 3, 4, 5, 6, 7, 8} -- number pool
    set weights to {5, 5, 20, 10, 20, 10, 15, 15} -- selection weight
    set n to random number from 3 to 8 -- selection count
    return {n, random(n, pool, weights)}
    on random(n, pool, weights)
    script o
    property ww : weights
    property pp : {}
    property kk : {}
    property rr : {}
    repeat with i from 1 to count pool
    repeat my ww's item i times
    set end of my pp to pool's item i
    end repeat
    end repeat
    repeat with i from 1 to count my pp
    set end of my kk to i
    end repeat
    repeat n times
    set k to my kk's some integer
    set end of my rr to my pp's item k
    set j to 0
    set i to 1
    repeat with w in my ww
    set j to j + w
    if k > j then
    set i to j + 1
    else
    repeat with h from i to j
    set my kk's item h to false
    end repeat
    set i to 1
    exit repeat
    end if
    end repeat
    end repeat
    return my rr's contents
    end script
    tell o to run
    end random
    --END OF SCRIPT 2
    Hope this may help,
    H
    Message was edited by: Hiroto

  • How can you generate Multiple random numbers from 1 to 49?

    I am very new at programming with the iPhone SDK and I need some help with a project I am working on. What I want to do is set up a window with 6 labels and 1 button. When the user clicks the button, the program will populate 6 randomized numbers each ranging from 1 to 49, and then place each of 6 numbers in a label. But each time the program ends and starts again the numbers cannot be the same, and also when the user clicks the button, no label can have the same number twice, so for example. If label 1 had the number 10, the other 5 labels cannot have that number until the button is clicked again. I know how to set up the interface, I just need the code. I would so greatly appreciate someone's help in this matter. I have been trying to do this for days and I cannot figure it out. Possibly someone who knows tons about Objective C programming can help me!
    Thank-you so very much!!

    I see that you're writing a lottery number generator. Perhaps the easiest way to do it is to emulate a real lottery: fill an array (NSMutableArray, probably) with the numbers between 1 and 49, pick one at random, remove that number from the array, and repeat. (You can think of the numbers as being the balls and the array as being the machine that pops them out.)
    One simple way to get the random indices needed is to extract six random bytes from Randomization Services using SecRandomCopyBytes, then loop over them, using the modulo operator (%) to select an index within the size of the array.
    And no, I'm not going to write your code for you. If I was going to do that, I could package and sell the app myself.

  • I need help with this program ( Calculating Pi using random numbers)

    hi
    please understand that I am not trying to ask anymore to do this hw for me. I am new to java and working on the assignment. below is the specification of this program:
    Calculate PI using Random Numbers
    In geometry the ratio of the circumference of a circle to its diameter is known as �. The value of � can be estimated from an infinite series of the form:
    � / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
    There is another novel approach to calculate �. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just � square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is � / 4.
    To simuluate the throwing of darts we will use a random number generator. The Math class has a random() method that can be used. This method returns random numbers between 0.0 (inclusive) to 1.0 (exclusive). There is an even better random number generator that is provided the Random class. We will first create a Random object called randomGen. This random number generator needs a seed to get started. We will read the time from the System clock and use that as our seed.
    Random randomGen = new Random ( System.currentTimeMillis() );
    Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
    A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. There is a method nextDouble() that will return a double between 0.0 (inclusive) and 1.0 (exclusive). But we need random numbers between -1.0 and +1.0. The way we achieve that is:
    double xPos = (randomGen.nextDouble()) * 2 - 1.0;
    double yPos = (randomGen.nextDouble()) * 2 - 1.0;
    To determine if a point is inside the circle its distance from the center of the circle must be less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is Math.sqrt ( xPos * xPos + yPos * yPos ). The radius of the circle is 1 unit.
    The class that you will be writing will be called CalculatePI. It will have the following structure:
    import java.util.*;
    public class CalculatePI
    public static boolean isInside ( double xPos, double yPos )
    public static double computePI ( int numThrows )
    public static void main ( String[] args )
    In your method main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by Math.PI. The quantity Difference in the output is your calculated value of PI minus Math.PI. Use the following number of throws to run your experiment - 100, 1000, 10,000, and 100,000. You will call the method computePI() with these numbers as input parameters. Your output will be of the following form:
    Computation of PI using Random Numbers
    Number of throws = 100, Computed PI = ..., Difference = ...
    Number of throws = 1000, Computed PI = ..., Difference = ...
    Number of throws = 10000, Computed PI = ..., Difference = ...
    Number of throws = 100000, Computed PI = ..., Difference = ...
    * Difference = Computed PI - Math.PI
    In the method computePI() you will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will call the method isInside() to determine if the point is inside the circle or not. This you will do as many times as specified by the number of throws. You will keep a count of the number of times a dart landed inside the circle. That figure divided by the total number of throws is the ratio � / 4. The method computePI() will return the computed value of PI.
    and below is what i have so far:
    import java.util.*;
    public class CalculatePI
      public static boolean isInside ( double xPos, double yPos )
         double distance = Math.sqrt( xPos * xPos + yPos * yPos );        
      public static double computePI ( int numThrows )
        Random randomGen = new Random ( System.currentTimeMillis() );
        double xPos = (randomGen.nextDouble()) * 2 - 1.0;
        double yPos = (randomGen.nextDouble()) * 2 - 1.0;
        int hits = 0;
        int darts = 0;
        int i = 0;
        int areaSquare = 4 ;
        while (i <= numThrows)
            if (distance< 1)
                hits = hits + 1;
            if (distance <= areaSquare)
                darts = darts + 1;
            double PI = 4 * ( hits / darts );       
            i = i+1;
      public static void main ( String[] args )
        Scanner sc = new Scanner (System.in);
        System.out.print ("Enter number of throws:");
        int numThrows = sc.nextInt();
        double Difference = PI - Math.PI;
        System.out.println ("Number of throws = " + numThrows + ", Computed PI = " + PI + ", Difference = " + difference );       
    }when I tried to compile it says "cannot find variable 'distance' " in the while loop. but i thought i already declare that variable in the above method. Please give me some ideas to solve this problem and please check my program to see if there is any other mistakes.
    Thanks a lot.

    You've declared a local variable, distance, in the method isInside(). The scope of this variable is limited to the method in which it is declared. There is no declaration for distance in computePI() and that is why the compiler gives you an error.
    I won't check your entire program but I did notice that isInside() is declared to be a boolean method but doesn't return anything, let alone a boolean value. In fact, it doesn't even compute a boolean value.

Maybe you are looking for

  • How to activate Events Calendar Sample Application's Weekly and Daily View?

    Does anyone know how to activate the Weekly and Daily View for the sample calendar application called "Events?" I am trying to generate, or incorporate, a calendar application based upon the sample application provided by Oracle. I have installed the

  • Share Photo Album - From: field

    When I share a photo album in iPhoto 08, the applications uses by .Mac alias instead of my default email address. Is their a setting to choose which email address iPhoto uses to send out the album invitation emails?

  • Re: Price matching policy for mobile phones sold with a contract

    Today I called my local store and they said they will not price match a contract price on a mobile phone.  When I look online, the contract price had a price guarantee.

  • CRMOD Presentation variable scope and usage in drilldown report

    Hello dear all, I have dashboard and presentation variables on dashboard promt. When selecting these presentation variables all work fine within dashboard. But when I drilldown to another report that also uses these presentation varibales its not wor

  • Msg E14 645 Not Found error

    Hi all, After completion of my SAPr/3 4.7installation, when I login to SAP system using GUI640 for the first time, I am getting the system message i.e. "Msg E14 645 Not Found", with this I am not able to logon to the system. Please help me to find th