Adding two random generated numbers together?

I'm writing a program for a class in which we have to simulate a two die rolling. So I got the computer to generate to random numbers, and now I need to add them to get the rolled die's sum. This info will then be organized into a chart. But I have no idea how to add to randomly generted numbers together, can anybody help me??
import java.util.Random;
import java.util.Scanner;
public class Test
    public static void main(String [] args)
        //Start
        Scanner in = new Scanner (System.in);
        int randDieNum1 = 0;
        int randDieNum2 = 0;
        Random randDieNum1List = new Random();
        Random randDieNum2List = new Random();
        //User Input
        System.out.print("Number of Rolls: ");
        int numToRoll = in.nextInt();
        //Testints
        //Loop
        for(int rolled = 0; rolled != numToRoll; rolled ++)
            int randDie1 = randDieNum1List.nextInt(6) + 1;
            int randDie2 = randDieNum2List.nextInt(6) + 1;
            System.out.println("RandNum1: " + randDie1);
            System.out.println("RandNum2: " + randDie2);
            int final = (int)randDie1 + (int)randDie2;
            System.out.println("Add: " + randDie1 + randDie2);
}

You can't call the variable "final" as that's a Java keyword. Try something like "sum" or "total".
(Also consider just using a single Random object and calling it twice to obtain the value for each of the dice.. And don't (cast) for the fun of it or as a talisman to ward off compiler messages.)

Similar Messages

  • Adding two special double numbers

    Adding two double numbers.
    say, 12543.34 and 42895.00 am getting in the decimal part .3999999.
    Now I want .34 instead .399999 and how??
    Can any body help me ??

    Read this (or search the forums--this question is asked at least once a day):
    http://docs.sun.com/source/806-3568/ncg_goldberg.html

  • Random generate numbers when pdf opens

    I have been trying to write a script which generates a random 12 digit number when the pdf opens.  I need to the number to show up in a certain read only field on the pdf.  I have tried writing the script in the document script and have been unsuccessful.  (The random number and another part of the the document will be used to pull information from it at a later date.)  Can anyone help me with a script so that I can make this possible?

    Do you want a new random number each time the file is opened? If so, enter
    this code as a document-level script (not inside a function!):
    this.getField("fieldname").value =
    Math.floor(Math.random()*Math.pow(10,12));

  • Writing a class using random generator in bluej

    Hello
    Im trying to write a class for a deck of cards. Im using a random generator but I dont know how to write the instance variable.
    I have to make 4 suits heart, club, spade, dimonds. and 13 for face value. I know how to random generate numbers. Like if I were making a slot machine to give me 3 numbers in a rage from 0-10. Thats just numbers. How do I random generate values of 1-13 and have it output a random suit? Also how do I make it say if its a jack king or queen? Do I need a constructor or how would I make the card with the face value of 13 suit heart and the card be a queen.
    before jumping down my throat about this being a homework assignment...yes it is but this step Im seeking help on there is no example for this type of generating.
    Thanks for any help
    Rewind

    Well, this is far from bullet-proof, but I think gets the basic idea across. This does sampling with replacement; if you wanted to do something like shuffle a deck of cards you'll need a smarter approach than this.
    import java.util.*;
    public class RandomCards {
      public static void main(String[] args) {
        Suit suit=new Suit();
        for (int i=0; i < 10; i++) {
          System.out.println(suit.nextSuit());
      private static class Suit {
        public static final String HEART="Heart";
        public static final String DIAMOND="Diamond";
        public static final String SPADE="Spade";
        public static final String CLUB="Club";
        private final String[] SUITS={ HEART, DIAMOND, SPADE, CLUB };
        private Gen suitGen=new Gen(0,3);
        public String nextSuit() {
          return SUITS[suitGen.nextInt()];
      private static class Gen {
        private int floor,ceiling;
        private Random rand;
        public Gen(int floor, int ceiling) {
          this.floor=floor;
          this.ceiling=ceiling;
          rand=new Random();
        public int nextInt() {
          return rand.nextInt(ceiling-floor)+floor;

  • Randomly Generate alpha-numeric strings?

    Hi, can somebody help me to randomly generate strings such as A1, B5, E 2, etc. The range for the values I need generated are [A-E][1-5]. I looked at lots of code for Random generating numbers, but found nothing related to what I need. I hope somebody can help me out here. Thanks!

    nevermind, i figured it out! thanks anyway

  • How to fetch records between two seq uence numbers?

    We have thousands of records with seq uence numbers in the oracle database, we need to retrieve a number of records between two seq uence numbers, i.e. to retrieve records between 100 and 200 seq uence numbers. Could some one help me to find a query to fetch records.
    I'll be waiting for your response..
    Edited by: sumant on Jul 27, 2010 12:42 PM

    Is this is what you are looking for?
    SQL> create table tab1 (id number);
    Table created.
    SQL> insert into tab1 values (1);
    1 row created.
    SQL> insert into tab1 values (2);
    1 row created.
    SQL> insert into tab1 values (3);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> select * from tab1;
            ID
             1
             2
             3
    SQL> select round(dbms_random.value(max(id)+1,max(id)+50)) random_number
      2  from tab1;
    RANDOM_NUMBER
               43
    SQL> select round(dbms_random.value(max(id)+1,max(id)+50)) random_number
      2  from tab1;
    RANDOM_NUMBER
               39
    SQL> select round(dbms_random.value(max(id)+1,max(id)+50)) random_number
      2  from tab1;
    RANDOM_NUMBER
               13 This will generate a random number that will be greater then the maximum value in the table and lower then the maxvalue + 50. Having the range starting from maxvalue in the table you will never get a number generated which already exists in the table.
    As you see in the above number genrated they are all between 4 and 53.
    If you want to increase the range from where the number are generated just increase the value 50 that I used in the query.

  • Randomly Generated Pixels

    Hi!
    I want to create a script that creates random (or near random) values for every single pixel of a document, similar to the "Add Noise..." filter, but with more control, such as "only b/w", "only grey", "all RGB" and "all RGB with alpha" and maybe even control over the probability distribution. Any idea how this could be tackled? Selecting every single pixel and applying a random color seems like something that would take a script hours...
    Why do I need this?
    I've started creating some filters in Pixel Bender (http://en.wikipedia.org/wiki/Adobe_Pixel_Bender). Since Pixel Bender doesn't really have any random generator (and workarounds are limited) I'm planning on passing on the random numbers through random pixel values. I'm well aware that this can only be used for filters in which Pixel Bender creates images from scratch, but that's the plan.
    Thanks!

    Understanding the details of the Add Noise filter is probably beyond the scope of just a short post.  Here is an approach to start learning what it does.
    - Take a 50% gray level and make it a Smart Object.
    -  Open up the historgram panel (should show a spike right at 50%)
    - Apply noise filter to Smart Object in monochrome building up from small percentages in small increments
    - You will notice that for this option above, you end up with a uniform probability function over the entire tonality spread at 50% applied for uniform distribution.
    There are a variety of ways to manipulate this function, through various blends.
    Please note a couple things
    1) I am using CS5 and though not documented anywhere that I have seen, the Noise Filter does work different than in CS4.  In CS4, if you run the same noise filter twice on two identical objects, my experience is that you get the identical bit for bit result ( a random pattern yet not independent of the next run of the filter).  Manipulating Probability Density Functions (PDFs) per my previous post requires that each run of the Noise Filter starts with a different "seed" so that the result is independent of the previous run.  CS5 does this where succesive runs will create an independent noise result.
    2) PS does not equally randomize R, G, and B.  There are ways to get around this yet wanted to give you a heads up.
    3) There are other ways to generate quick random patterns outside of PS and bring them in (using scripts).   You would need to understand the format of the Photoshop Raw file.  This type of file contains bytes with just the image pixel data.  These types of files are easy to create and then load into PS. From a script (or even faster call a Python script) create this file and then load it into PS as a Photoshop Raw format file and use as an overlay.  There is not question that this is faster than trying to manipulate individual PS pixesl through a script.
    4) Please not the under Color Settings there is an option called Dither.  If this is set, there are  times where PS adds nosie into the image (I leave mine turned off).  If is used in a number of places in PS other than what the documentation implies (more than just when moving between 8 bit color spaces)
    Good luck if you are going after making a plug-in.  I have never invested in that learning curve.  Good luck.

  • How to make a random generator with a max and a minimum

    hello
    can anybody telle me how to make a random generator for numbers with a maximum and minimum input
    thanks in advance

    Hi suske,
    If you want a random day for a given month, this is how I would do it.
    Hope this helps,
    -D
    Message Edited by Darren on 02-02-2006 01:35 PM
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman
    Attachments:
    Days_per_month.jpg ‏32 KB

  • Nokia lumia 610 randomly dials numbers

    I have a Nokia Lumia 610 and for some odd reason last two weeks it randomly dials numbers either mobile or landline.  When its sat on the kitchen table, it just dials it, more oddly it switches to loud speaker and it does it about 10-15 times same number one after another.
    Switched it off and back on and for a few days its ok and then it does it again.  Anyone ever come across this and is it fixable

    Hi genpower,
    Welcome to Nokia Support Discussions!
    Do you have a screen protector on the screen? Sometimes a screen protector can do selections on it's on, especially if it is of a lower quality. If so, try to remove the film to see if it fixes the issue. 
    You could try to reset your phone, which will reinstall the operating system on the phone. To reset your phone, go to settings > about > reset your phone. It is recommended to synchronise all your media files before doing this, as it will remove all user files on the phone. Please note that you will lose all your text messages in the process. 
    Let us know how you get on!
    Puigchild
    If you find this post helpful, a click upon the white star at bottom would always be appreciated.
    If it also solves your problem, clicking ACCEPT AS SOLUTION below it will benefit other users!

  • QCPatch 'Random Generator' Broken Seed?

    Hi there all,
    Just putting this out there - perhaps I'm wrong, but want some other QC developers who are more experienced to compare with.
    Quartz Composer Patch "Random Generator" - one of the inbuilt patches available.
    Its purpose is to generate random numbers between a range, and supply the number on its output port.
    To this end, it works fine.
    My problem with this patches behavior occurs when it is nested in a macro patch, and that patch is then duplicated (purpose obvious).
    *The duplicated macro patch appears to also copy the Random Generators' base seed.*
    For example I have the same picture resulting from Random Generators nested inside a macro patch that contains processing for a random choice of image to a sprite.
    The only way i could work around this (and this may help others with the same problem) was to Publish the Input ports all the way up to the root level patch, and supply new instances of a Random Generator for each instance of the duplicated macro patch.
    Then I received fresh random seeds from the generator and different images were selected for output to my nested sprite.
    Awfully inconvenient given that each macro had 4 levels of nesting using objects like render in image, 3D transformation and Lighting - all patches that require nesting, and also reset your ports being passed to a parent, meaning you have to - 're-map' the Published Inputs with every layer of nesting. Not to mention the fact that the root level of the document is cluttered all to **** with millions of Random Generator patches.
    Anyone get this behavior?
    Please let me know if I'm just screwing my design up, or if this is encountered by you too and we should report it as a bug. (Ive only been devving QC for several weeks straight, so I'm want to actually report it as a bug yet).
    Many thanks in advance,
    Wilks.

    A random created with the same seed will give the same set of random numbers.
    Take out the Random creation from the loop
    try
                 BufferedWriter out = new BufferedWriter(new FileWriter("c:/test.txt"));
                    //Create Random here.
                     Random r = new Random( );//No need for any seed
                 for (int i = 0; i < 1000; i++)
                      out.write(String.valueOf(r.nextInt(9)));
                 out.close();
    catch (IOException e)
    [url http://www.feedfeeds.com/feedtv]Feed Your Feeds

  • Two objects have joined together - how do I split them again?

    I have added two objects to a pdf, and they have mysteriously merged together. This is now causing me a real problem. I have tried deleting the text that is in the first object and recreating it, but Acrobat just joins the two objects together again!
    Am I missing something here? Why is this happening?
    Can I split the two objects again or do I have to do something else entirely?
    Thanks in anticipation
    Rob

    Ok, I think I see what happened. There are actually no permanent text
    objects in a PDF at all.
    What happens is that Acrobat looks at all the text on the page, where
    it is, and what is close. Then it decides how to split these up: what
    you see now seem to be text objects.
    So if you add two lots of text close together, they have no special
    identity, and will indeed seem to become one object.
    Aandi Inston

  • Labview random generator leds

    Hey Labview users,
    I'm a novice with labview and i have to solve the next exercise. Create a random generator 10 which generates random numbers between 0 and 100.
    Provide between 2 numbers generated a delay of 1s.
    Provide also 3 LEDs that light up as follows:
    - Red LED: 70 <random number
    - Green LED: 30 <random number <70
    - Orange LED: random number <30
    Only when the 10 random numbers are generated, enter this  1 dimensional, profiled collection (1D array).
    Can anybody show me the block diagram
    Can somebody help me please ? It's quite urgent.(i have untill saterday 26/1)
    Any solution is welcome !

    Well, if you have to have this done, you hade better get on with it.
    A couple hints:
    The random number generator built into LV puts out a DBL float value between 0 and 1.
    You can use the threshold function to determine which of the three LEDs should be on.
    You know ahead of time that the VI needs to loop 10 times, so you can use a for loop.
    There is a wait function in LV that you can use to generate the 1 sec delay.
    Beyond this, we will not write your homework for you. We don't need your degree, we have degrees of our own.
    Post code and we will help you by answering specific questions.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Adding two generic number types

    Hi all,
    As a small exercise I am trying to devise a generic maths class that can add two numbers together either Integer, Float and Double types.
    I have written the following code
    class Test {
    public static void main(String args[]) {
         MathClass<Integer> integers = new MathClass<Integer>();
         Integer i= new Integer(2);
         System.out.println(integers.add(i,i));
    class MathClass<T> {
         public T add(T a, T b) {
              return a + b;
         public T subtract(T a, T b) {
              return a - b;
         public T multiply(T a, T b) {
              return a * b;
         public T divide(T a, T b) {
              return a / b;
    }But I get a compile error which says that I can't use the + - * / operators on T.
    Yet something like the following code works
    public class Test2 {
       public static void main(String[] args) {
         Integer i = new Integer(2);
         Integer o = new Integer(2);
         System.out.println(i + o);
    }Is there a way to make the generic maths class work as I would like?

    Even with the UpperBound as Number it will not be able to work as the compiler will not be able to apply autoboxing feature with Number. Number class has byteValue(), intValue(), floatValue() and doubleValue() as method, so Number class is not a spefic datatype class.
    This will work because of the feature autoboxing.
    public Integer addInteger(Integer a, Integer b) {
              return a + b;
    This will not work...
         public Number addInteger(Number a, Number b) {
              return a + b;
         }

  • Trying to build a random generator

    Hi, I am quite new to java and was wondering how do I complete building this program.
    The objective of the program is to randomly generate 100 2 digit odd integer values.
    I can generate the values but I don't know how to sieve only 100 odd integers.
    I am also supposed to find the maximum, minimum and average of all the numbers generated. I can find the average but can't seem to find maximum and minimum.
    I also need to point out the location of the maximum and minimum which I do not have a clue on how to do.
    Lastly, my program is suppose to loop when keyed in 'y' or 'Y'. I think I have done that.
    My codes are as below
    import java.io.*;
    class Question2
         public static void main (String args []) throws IOException
              BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
              Question2 theClass = new Question2();
              String strValue = "";
              int value = 0;
              int random [] = new int [100];
              int l= random.length;
              int max=0, min=0;
              int sum = 0;
              do {
              System.out.print("Enter 'Y' to Start / Begin ");
              strValue = stdin.readLine();
              if (strValue.equalsIgnoreCase("Y")){
              for(int i = 0; i<l ; i++)
                   if (i%10==0)
                        System.out.println("");
                   random[i] = randomNumber(value);//recall method to generate numbers
                   System.out.print(random[i] + " ");
                   int maximum = random;
                   max = findMaximum(maximum);//recall method for maximum
                   int minimum = random[i];
                   min = findMinimum(minimum);//recall method for minimum
                   sum = sum + random[i];
              else
              break;
              int average=0;
              average = findAverage(sum);//recall method for average
              System.out.println("\nThe average is " + average);
              System.out.println("The Maximum Number is " + max);
              System.out.println("The Minimum Number is " + min);
         }while (strValue.equalsIgnoreCase("Y"));     
              //random number generator
         public static int randomNumber (int value)
              int choose=0;
              choose = 10 + (int)(Math.random()*89);
              return choose;
         //maximum number generator
         public static int findMaximum(int maximum)
              int maxi = 0;
              if (maximum>maxi)
              maxi=maximum;
              return maxi;
         //average generator
         public static int findAverage (int sum)
              int avg = 0;
              avg = sum/100;
              return avg;
    //minimum generator
         public static int findMinimum(int minimum)
              int mini = 0;
              if (minimum<mini)
              mini = minimum;
              return mini;
    Thank you.

    Yes, but it guarantees that the process will be
    complete after 100 iterations. The discarding
    strategy will be completed in 200 iterations, on
    average, and there is no guarantee that once in a
    while, it will not take 1000 iterations.Pshaw. It's not that expensive to generate a new
    number. Heck, Random.nextInt(int) numbers are
    generated by throwing away numbers. There's a chance
    that it will never return.
    And if you are worried about that, I've got a server
    to sell you.
    ~CheersI myself (almost) always prefer clarity over performance. In this case,
    I think 2 * n + 1 produces both. You may say that I overdo it, for such
    a simple exercise. This I don't dispute. By the way, the way nextInt() is
    implemented is irrelevant, don't we like encapsulation anymore?

  • How to add two different page numbers in a single page

    How to add two different page numbers in a single page? One is for page number of the whole article, the other one is for page number for each chapter in the article.

    It's quite complicated, see
    Two Page Numbering Schemes in the Same Document.
    Regards, Hans Vogelaar (http://www.eileenslounge.com)

Maybe you are looking for

  • Calls from cucm to CME not working-unknown number

    hi all we have cucm 9.1 and gateway 2911 on the side A and on the side B we have uc540 , we have configured tunnels between 2911 and uc540, calls from cucm SideA to uc540 Side B is ok and working fine. now we have one 9951 phone which gets ip from uc

  • MII Development - Quality - Production promotion

    Hi Does anyone has experience in promotion of MII projects from Development to Production via SAP standard transporation?. What we currently doing is transfer (export imports) of MII projects from one server to another server (i.e Development server

  • Iphone 6 wont update and restore to factory settings

    i update my iphone 6 to os 8.1.2 then an icon 'connect to itunes' appear, when i connect to itunes it says "your iPhone can't be updated; you must restore it to factory settings." Then i select restore then a prompt appears again saying "Are you sure

  • RX9800PRO 128MB Rendering Issues

    I recently purchased the MSI RX9800Pro 128MB card from newegg.  On initial install of the catalyst 4.7 drivers everything was well.  I am upgrading from a Geforce 4 Ti4600, so it's should be quite an upgrade, yet I have 2 issues. (i did a full uninst

  • Select layer function in actions

    I have three layers with text in different languages. I want to save them to three different PNG files. I've tried to do action which select the layer, hide it and save it. Then select another layer and do the same. But selecting layers is not record