How to change double i = Math.random(); value to (int) value

I am trying to find out how to convert a given double value to integer, which is, to conver double myNumber = Math.random() to (int) value. Here is the sample program look like this.
Thank you for the help.
import javax.swing.JOptionPane;
public class numbers
public static void main(String[] args)
int upperLimit = Integer.parseInt(JOptionPane.showInputDialog
(null, "Enter the upper range integer."));
double myNumber = Math.random();
//Test of Random numbers.
System.out.println("The Upper random number limit is: " +
myNumber * upperLimit);
} //End of main.
} // End of class.

Not sure exactly what you want and why you want to change the double to an int. I'm assuming by this you want to generate random integers, from 1 to the upper limit the user enters? If so, this is how I would do it:import java.util.*;
import javax.swing.*;
public class Numbers
    public static void main(String[] args)
        int upperLimit = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the upper range integer."));
        Random r = new Random();
        int myNumber = r.nextInt(upperLimit) + 1;
        System.out.println(myNumber);
}

Similar Messages

  • How to change double random value to int value?

    I need to change double random number to int in my program. Please help
    Here's my program
    import java.io.*;
    class GuessingGame
    public static void main( String[] args ) throws IOException
    int guess;
    BufferedReader stdin = new BufferedReader(
    new InputStreamReader( System.in ) );
    String input;
    double somevalue;
    int attempt = 0;
    boolean win = false;
    somevalue=Math.random()*10 ;
    while ( attempt < 3 && !win )
    boolean correct = true;
    //First Guess
    System.out.println("\nI am thinking of a number from 1 to 10.");
    System.out.println("You must guess what it is in three tries.");
    System.out.println("Enter a guess:");
    input = stdin.readLine();
    guess = Integer.parseInt( input );
    if ( guess != somevalue )
    correct = false ;
    System. out.println("Wrong");
    //Second Guess
    System.out.println("Enter a guess: ");
    input = stdin.readLine();
    guess = Integer.parseInt( input );
    if ( guess != somevalue )
    correct = false ;
    System. out.println("Wrong");
    //Third Guess
    System.out.println("Enter a guess: ");
    input = stdin.readLine();
    guess = Integer.parseInt( input );
    if ( guess != somevalue )
    correct = false ;
    System. out.println("Wrong");
    //Result
    if ( correct )
    System. out.println("Right");
    System.out.println("You won the game!");
    win = true;
    else
              System.out.println("The correct number was:"+ somevalue);
    System.out.println("You lost");
    attempt = attempt + 1;

    Ceranith, thanks. It works now. You were very helpful. I searched and found your answer on a similar question using nextInt(int n). I tried to use that approach to my program (for learning purposes)as well, but it didn't work. Could you help to find out what's wrong?
    Here it is:
    import java.io.*;
    import java.util.*;
    class GuessingGame
    public static void main( String[] args ) throws IOException
    int guess;
    BufferedReader stdin = new BufferedReader(
    new InputStreamReader( System.in ) );
    String input;
    int attempt = 0;
    boolean win = false;
    int n=10;
    Random numb = new Random();
    int somevalue = numb.nextInt(int n)+1;
    while ( attempt < 3 && !win )
    boolean correct = true;
    //First Guess
    System.out.println("\nI am thinking of a number from 1 to 10.");
    System.out.println("You must guess what it is in three tries.");
    System.out.println("Enter a guess:");
    input = stdin.readLine();
    guess = Integer.parseInt( input );
    if ( guess != somevalue )
    correct = false ;
    System. out.println("Wrong");
    //Second Guess
    System.out.println("Enter a guess: ");
    input = stdin.readLine();
    guess = Integer.parseInt( input );
    if ( guess != somevalue )
    correct = false ;
    System. out.println("Wrong");
    //Third Guess
    System.out.println("Enter a guess: ");
    input = stdin.readLine();
    guess = Integer.parseInt( input );
    if ( guess != somevalue )
    correct = false ;
    System. out.println("Wrong");
    //Result
    if ( correct )
    System. out.println("Right");
    System.out.println("You won the game!");
    win = true;
    else
              System.out.println("The correct number was:"+ somevalue);
    System.out.println("You lost");
    attempt = attempt + 1;

  • How to change double to int?

    i got a double
    double x
    x = 3 * 1.2
    how to change x to int type?
    thx a lot

    You can't change x, it's declared as type double.
    You can retrieve the value of x as an int by using a cast:
    int y = (int) x;

  • How to change double spaces to single space

    For some reason that I don't know about, the majority of the
    time that I download a PHP or HTML document from the web server to
    my local PC the document gets double spaces injected into each line
    of code. In HomeSite there is a simple command in the menu to
    change double spacing to single spacing. Why does Dreamweaver not
    have this, or if it does, then where is it? I cannot spend all of
    my time mannually removing each double spaced line. I tried the
    search and replace for this, but then I loose my tab formatting and
    it makes the code hard to read. Can anybody help or point me to an
    extension that works for this or sdomething? Or, do I just need to
    reload HomeSite and work in it instead of Dreamweaver?

    "carl@csi" <[email protected]> wrote in
    message
    news:fgn8sd$bn4$[email protected]..
    > For some reason that I don't know about, the majority of
    the time that I
    > download a PHP or HTML document from the web server to
    my local PC the
    > document
    > gets double spaces injected into each line of code. In
    HomeSite there is a
    > simple command in the menu to change double spacing to
    single spacing.
    > Why
    > does Dreamweaver not have this, or if it does, then
    where is it? I cannot
    > spend
    > all of my time mannually removing each double spaced
    line. I tried the
    > search
    > and replace for this, but then I loose my tab formatting
    and it makes the
    > code
    > hard to read. Can anybody help or point me to an
    extension that works for
    > this
    > or sdomething? Or, do I just need to reload HomeSite and
    work in it
    > instead of
    > Dreamweaver?
    Open the find/replace dialog, and check "Use regular
    expressions".
    then type the following in the search box
    \n\s*\n
    and type Ctrl-Enter in the replace box
    this should replace double line-breaks (with or without
    whitespace between
    them) with a single one.
    Joris van Lier

  • How should I change from Object value to int value?

    ArrayList ap = new ArrayList();
    ap.add(10);
    I want int value...
    How should I do?
    int a22 =(int)ap.get(0);
    It's not working.
    Help me.

    This is tricky. Before 1.5, you could not do ap.add(10), you would have to do
    ap.add(Integer.valueOf(10)); // OR
    ap.add(new Integer(10));
    This is called autoboxing and the compiler provides the extra code for you.
    If you want to get it out as an int, you have to choices
    1) Use generics
    List<Integer> ap = new ArrayList<Integer>();
    ap.add(10);
    int ten = ap.get(0);2) Cast
    List ap = new ArrayList();
    ap.add(10);
    int ten = ((Integer)ap.get(0).intValue();

  • How to change what is used for the condition base value

    I have a new condition type that I want to always get its conditon base value from a list price total in the pricing procedure.
    Do I need to do this in a routine?  If yes, can you give more details on what should be in the routine.
    Thanks

    The new condition(ZXXX) which should always have the base value amount of the list price -
    Settings
    ZXXX in transaction v/06- when defining this condition you have a field under Master data - to use it as reference condition type
    over here you can mention the condition for the list price. than it should work.
    Hope this helps
    Cheers
    jasmeet

  • Hopefully easy answer. How can I get a slider to only have integer values?

    I'm trying out a slider from the example page to let users chooice 5-100, but the slider also lets values be doubles. Is there any way to limit the slider to only lock on to values when they're doubles?

    This seems to work, the code below forces the slider position to be a power of 2 (1,2,4,8,16,32,64,128).
    new Slider(1, 128, 64) {{
            valueProperty().addListener(new ChangeListener<Number>() {
              @Override
              public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                double value = (Double)newValue;
                int closestPowerOf2 = (int)Math.round(Math.log(value) / Math.log(2));
                if((int)value != (1 << closestPowerOf2)) {
                  setValue(1 << closestPowerOf2);
            setMajorTickUnit(25);
            setShowTickMarks(true);
            setShowTickLabels(true);
    }};

  • How to change crystal report data field at runtime ?

    Hello everyone,
    I have a Crystal Report file ,which i am using to generate report for my windows form project .
    In that report i have a filed called as Quantity which data type is set as decimal, the requirement is like that the number of value those comes after decimal point that should be set according to the value which is given by the user at the run time .
    For eg: If user gives 1 at the run time then the report Qty field value set one value after decimal point. Like 12.1
    if user gives 2 then Qty field the value is 12.22 like tat  but user can give from zero to any number.. and if it is zero it should not show decimal
    Note: The main idea hear is how to change the filed in Crystal Report decimal point value by using code(or we say writing code we need to set manually as user input it will change)
    Can any body help me how to solve this issue .
    S.K Nayak

    I think you could probably make the field you see a formula field and take a parameter as the number of decimal places.
    totext converts a number to a string.
    totext({decimalField}, 2)
    That's 2 decimal places.
    You could probably substitute a {parameter} for that 2.
    If not then you could substitute an entire formula.
    To explore formulas:
    foreach (FormulaFieldDefinition f in rpt.DataDefinition.FormulaFields)
    MessageBox.Show(f.Name);
    // f.Text = your new formula
    Where rpt is an instantiated report.
    Or add another string field which you display in the column and do the calculation with the original decimal.
    Hope that helps.
    Recent Technet articles:
    Property List Editing;  
    Dynamic XAML

  • Comparing a single int to more than one int value?

    Hi is there a way to compare a single int value amongst several ints in one go?
    i know i could do if statements that can compare each int one by one but i was wondering if there is an easier way? like comparing all values amognst eachother
    somthing like
    int i;
    int a,b,c,d,e,f,,g;
    //ints a-g assigned some random numbers
    if(i == a,b,c,d,e,f,g)
          //do somthing here
    }

    i found out a way. i tried this way by using nested for loops and an if statement that compares every single value amongst eachother
    for(int q=0; q < 5; q++)
                ran[q] = (int)(java.lang.Math.random()*52);
            for(int x = 0; x < 5;x++)
                for(int z = 0; z < 5; z++)
                    if(x != z && ran[x] == ran[z])
                        ran[x] = (int)(java.lang.Math.random()*52);
            }

  • How to change default value in a table using ALTER TABLE

    Hi,
    How to change default value in a table
    I have a table TEST which has 2 fields CODE of Datatype VARCHAR2(10) and Indicator as VARCHAR2(1).
    I want to change the default value using ALTER TABLE TEST of field Indicator to 'I'.
    Any help will be needful for me
    Thanks and Regards

    user598986 wrote:
    Hi,
    How to change default value in a table
    I have a table TEST which has 2 fields CODE of Datatype VARCHAR2(10) and Indicator as VARCHAR2(1).
    I want to change the default value using ALTER TABLE TEST of field Indicator to 'I'.
    ALTER TABLE  test
    MODIFY (indicator DEFAULT 'I'); 
    Incidentally, INDICATOR is a keyword in Oracle, so you may have problems using it as a column name. If so, you'll have to enclose the column name in double-quotes, and be careful to use capital letters inside the quotes.
    Edited by: Frank Kulash on Aug 26, 2009 11:42 AM

  • Help!!!!!  anyone know how to change a Double to an int??

    Help!!!!! anyone know how to change a Double to an int?? for use in an array[int].

    I don't know why would you want to depend on a double value to build your array but programmatically just use plain old cast: i = (int) double_value;
    Keep in mind though, the integer value will be truncated.

  • How to use Math.random() to generate an integer within a range

    How can I generate a random integer from 1 to 10 using the Math.random() method?
    Thanks.

    Then why do i get this compile-time error?
    found   : double
    required: int
                        matrix[i][j] = (int) 11 * Math.random();
    matrix is an array of integers:
    String colNumStr = JOptionPane.showInputDialog("Please specify the number of rows");
        String rowNumStr = JOptionPane.showInputDialog("Please specify the number of columns");
        int rowNumInt = Integer.parseInt(rowNumStr);
        int colNumInt = Integer.parseInt(colNumStr);
        int [][] matrix = new int [rowNumInt][colNumInt];

  • How to Change a Default Value from Drop Down Box displayed in Web Dynpro?

    Hi,
    How to Change a Default Value from 'High' to 'Low'  in a Drop Down Box for RANGE field displayed in Standard Web Dynpro Component.  I saw a Default Value set for a RANGE field  in View Context When I select that field and click on Display. I am seeing Default Value set it to 'HI'. Please let me know how to change from HIgh to Low.
    I appreciate your help!
    Thanks,
    Monica

    hi,
    use the set_attribute( ) method now to set the attribute with a particular key eg HIGH in ur case
    // u can use the code wizard( control +f7) this code will be auto generated when u select the
    //radio button to read the context node
    DATA lo_nd_cn_node TYPE REF TO if_wd_context_node.
      DATA lo_el_cn_node TYPE REF TO if_wd_context_element.
      DATA ls_cn_node TYPE wd_this->element_cn_node.
    * navigate from <CONTEXT> to <CN_NODE> via lead selection
      lo_nd_cn_node = wd_context->get_child_node( name = wd_this->wdctx_cn_node ).
    * get element via lead selection
      lo_el_cn_node = lo_nd_cn_node->get_element(  ).
    * set single attribute
      lo_el_cn_node->set_attribute(
          name =  `ATTribute name.`
          value = 'LOW' ).
    it will solve ur query ..
    also refer to this component
    wdr_test_events -> view dropdownbyidx and dropdownbykey ->method name onactionselect.
    regards,
    amit

  • How to change default Current Flag values for SCD2?

    I'd be curious to find out how to change default Current Flag values for SCD2 (instead of 0/1 to use N/Y)
    Probably I can change IKM module .... is there another way?
    Thanks

    Hi,
    You need change the IKM. This values are hardcode in the IKM.
    You can create a new IKM and the values used are a options of the IKM.
    Regards
    Edited by: Uthred on May 18, 2009 4:27 PM

  • How to change default value of a parameter and LOV attached to a parameter

    Hi All
    I am new to discoverer reports and I need to accomplish the following tasks:
    1. Need to change the SQL query of a discoverer report
    2. Need to change the default value of parameter ( from constant to current month). In the discoverer plus responsibility when I open the report and go to tools>>parameter>>edit
    I can see the constant default value given there. On the right hand side there is a drop down which says 'Value'. I guess if i need to put a SQL as defaul value I need to change the drop down to sql or something and then put the SQL. Problem is the drop down is froezen and I cannot change it.
    Even if I try to create a new parameter/report.
    3. Need to change the LOV associated to the item on which the parameter is based.
    I have the discoverer plus responsibility attached to myself and do not have the discoverer administrator tool (desktop developer tool like forms 6i). My questions are:
    1. Can I change the SQL query by using discoverer plus responsibility or do I need discoverer administrator tool?
    2. Any help on how to get the default value from an SQL query? currently it is a constant value.
    3. Is there any way to figure out is the LOV is madeup of fixed constant values (like independednt value set) or they are fetched from some sql query(table validated value sets)?
    Any pointers/solutions will be highly appriciated!!!
    Thanks in advance.
    Thanks and Regards,
    Shashank

    HI,
    Need to change the SQL query of a discoverer reportThe discoverer generate the SQL according to the item, calculation and conditions designed in the worksheet.
    You cannot edit a specific worksheet SQL.
    In order to change the SQL you need to change the worksheet using the "Edit-> worksheet" from the menu.
    To change the SQL generated inside the folders you need to do that using the administrator.
    Need to change the default value of parameterYou cannot use SQL statements for the parameter default value. it is not supported. if you need default you can use only constant (as it was). otherwise you can set the parameter to be optional and then add to this condition an OR saying that <item>= NVL(:Parameter,<your default>)
    as <your default> you can use calculations so that if for example you want the current date you will create a calculation containing: SYSDATE.
    Is there any way to figure out is the LOV is madeup of fixed constant values (like independednt value set) or they are fetched from some sql query(table validated value sets)?They are based on SQL, even they are const then you will see it as
    select 'a','b'... from dual
    you can find the LOV (called item classes) in the administrator.
    Go to the item your condition is based on and see its properties.
    In the properties you should see the item class it uses.
    Close the properties and go to the item classes tab, search for this item class and figure the folder it came from.
    This is the folder you need to change in order to change the LOV.
    Hope it helped a bit, you sure asked several big questions...
    Tamir

Maybe you are looking for

  • Error message while creating transfer order

    Hi Experts, My objective is to create a transfer order from a transfer requirement programatically. I am trying to create a transfer order using FM L_TO_CREATE_TR programatically. Prior to this FM, I am calling FM L_TR_CREATE to create a transfer req

  • Problem pairing bluetooth keyboard?

    I feel ridiculous posting this because it's essentially publicizing my own stupdity, but I noticed a lot of other people having the same problem I had. I had been using my aluminum bluetooth keyboard, it was working great. Then it stopped working-- I

  • Games/RAM on MacBook Pro 15"

    I have recently purchased a MBP 15" with the base graphics and specs. When I go to play a game, sometimes it really lags, almost to the point of unplayability. The game I'm playing when this happens is Minecraft. I don't know if Minecraft is a RAM ho

  • About decode statement

    hi Gurus can anybody tell me how to convert following if condition into decode also i put my isnumber funtion. Thanks Vijay if (SOURCE = 'QU'  AND RSLT_NBR = -999999.999999) then null else if SOURCE = 'LC' AND RSLT_NBR = 0 AND IS_NUMBER(RSLT_TXT) the

  • How to boost search in UCM?

    I am talking about performance tuning. one option may be to increase the memory, but what should be the memory size.and where to check the current memory size of my content server? Thanks.