Desperate HELP with Random Numbes in an Array & Do / While

Please somebody help, I have been working this problem for over 7 days now and can't get it. I have tried everything from a while to a do while to this and that. I need to have an Array of 8 that when run will produce random numbers for output between 15 to 25. I CAN"T GET IT PLEASE HELP. I am new to JAVA and have done everything I can think of to resolve this. I even have purchased a new book and looked at every site trying to find a solution. PLEASE HELP! Here it is:
import javax.swing.*;
public class RandomArray{
public static void main (String [ ] args) {
JTextArea outputArea = new JTextArea ( );
int myArray [ ]; //array declaration
myArray = new int [ 8 ]; //allocating memory
String output = "Array values at initializatioon ";
output += "\nIndex\tValues";
for ( int i = 0; i < myArray.length; i ++)
output += "\n" + i + "\t" + myArray [ i ];
output += "\n\nArray values after assigning values within the range of 15 and 25";
do {( int i = 0; i <myArray.length; i++)
     while     myArray [ i ] = 15 + (int) (Math.random ( ) * 25);
output += "\n" + i + "\t" + myArray [ i ];}
outputArea.setText (output);
JOptionPane.showMessageDialog (null, outputArea,
"Array Value before and after",
JOptionPane.INFORMATION_MESSAGE);
     System.exit ( 0 );
The output that I need is in two columns one with the initial array 0-7 and the second should be random numbers 15-25. Please help, please

here you are :
import javax.swing.*;
public class RandomArray
public static void main (String [ ] args)
     JTextArea outputArea = new JTextArea();
     int       myArray [] = new int[8];
     String output = "Array values at initializatioon ";
     output += "\nIndex\tValues";
     for (int i = 0; i < myArray.length; i ++)
          output += "\n" + i + "\t" + myArray [ i ];
     output += "\n\nArray values after assigning values within the range of 15 and 25";
     for (int i = 0; i < myArray.length; i++)
          myArray [ i ] = 15 + (int) (Math.random ( ) * 10);
          output += "\n" + i + "\t" + myArray [ i ];
     outputArea.setText(output);
     JOptionPane.showMessageDialog (null, outputArea,
          "Array Value before and after",
          JOptionPane.INFORMATION_MESSAGE);
     System.exit(0);

Similar Messages

  • I need help with random number in GUI

    hello
    i have home work about the random number with gui. and i hope that you can help me doin this application. and thank you very much
    Q1)
    Write an application that generates random numbers. The application consists of one JFrame,
    with two text fields (see the figures) and a button. When the user clicks on the button, the
    program should generate a random number between the minimum and the maximum numbers
    entered in the text fields. The font of the number should be in red, size 100, bold and italic.
    Moreover, if the user clicks on the generated number (or around it), the color of the background
    should be changed to another random color. The possible colors are red, green blue , black ,cyan
    and gray.
    Notes:
    �&#61472;The JFrame size is 40 by 200
    �&#61472;The text fields size is 10
    this is a sample how should the programe look like.
    http://img235.imageshack.us/img235/9680/outputgo3.jpg
    Message was edited by:
    jave_cool

    see java.util.Random

  • How to fill array with random number?

    I need to fill a 3-dimensional array that has user-controlled dimension sizes with random numbers (1-10). I'm unsure of how to do this. I feel like I have to use the initialize array and maybe the build array functions somehow but I'm not entirely sure. Any help would be appreciated. Thanks.

    Something like this
    Kudos are always welcome if you got solution to some extent.
    I need my difficulties because they are necessary to enjoy my success.
    --Ranjeet
    Attachments:
    Array with random number.vi ‏9 KB

  • Need help with random string arrays

    Hi, I could really use some specific advice about how to randomize and display strings. I'm trying to create an applet that displays a list of 12 chores and a list of four people for whom the chores should be distributed to. So far I have set up the code to display the chores list in the first column and what I'm tring to do is then randomly assign each persons name 3 times in the second column. I'm not getting any error messages but the problem is that I can't seem to get the names to appear only 3 times.
    // Random generator = new Random();
    // JButton assignChores = new Button("Assign Chores")'
    // JTextArea outputArea = new JTextArea("");
    // ect....
    public void actionPerformed(ActionEvent e) {
    String[] chores = {"Living Room",
    "Dining Room",
    "Kitchen",
    "Boy's Room",
    "Garbage",
    "Backyard",
    "Pets",
    "Front Bathroom",
    "Back Bathroom",
    "Laundry",
    "Computer Room",
    "Parent's Room"};
    String[] person = {"Mom",
    "Dad",
    "Son",
    "Daughter"};
    int[] numIndex = new int[13];
    String output = "Chores" + "\t" + "Person";
    output += "\n________________________________\n";
    // I feel relatively certain that a while statement should go
    // here but I'm lost as to how I should go about this.
    for (int i = 1; i < numIndex.length; i++) {
    int arrayIndex = generator.nextInt(person.length); // generate a random number based on the number of people
    output += "\n" + chores[numIndex[0]++] // display the chores list in column 1
    + "\t" + person[arrayIndex]; // then randomly display the names in column 2
    output += "\n________________________________\n";
    outputArea.setText(output);
    JOptionPane.showMessageDialog (null, outputArea,
    "Chores List", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);

    Hi,
    Here's even a more elegant twist on the problem.
    import java.util.*;
    class FamilyMember
      private String name;
      private ArrayList chores;
      private final int MAX_CHORES = 3;
      public FamilyMember( String name )
        this( name, null );
      public FamilyMember( String name, Collection chores )
        this.name = name;
        setChores( chores );
      public String getName()
        return( name );
      public Collection getChores()
        return( chores );
      private void initArray()
        if( chores == null )
          chores = new ArrayList();
      public void setChores( Collection newChores )
        if( newChores != null )
          initArray();
          if( newChores.size() <= MAX_CHORES )
            Iterator it = newChores.iterator();
            while( it.hasNext() )
              chores.add( it.next() );
      public boolean addChore( String newChore )
        boolean outBool = false;
        initArray();
        if( chores.size() < MAX_CHORES )
          chores.add( newChore );
          outBool = true;
        return( outBool );
      public void setName( String newName )
        name = newName;
    class Chore
      private String name;
      private boolean assigned;
      public Chore( String name )
        this.name = name;
      public String getName()
        return( name );
      public void setName()
        this.name = name;
      public void setAssigned( boolean newAssigned )
        assigned = newAssigned;
      public boolean isAssigned()
        return( assigned );
    public class ChoreLister
      public static void main(String[] args)
        Chore[] chores = { new Chore( "Living Room" ),
                           new Chore( "Dining Room" ),
                           new Chore( "Kitchen" ),
                           new Chore( "Boy's Room" ),
                           new Chore( "Garbage" ),
                           new Chore( "Backyard" ),
                           new Chore( "Pets" ),
                           new Chore( "Front Bathroom" ),
                           new Chore( "Back Bathroom" ),
                           new Chore( "Laundry" ),
                           new Chore( "Computer Room" ),
                           new Chore( "Parent's Room" ) };
        FamilyMember[] fm = { new FamilyMember( "Mom" ),
                              new FamilyMember( "Dad" ),
                              new FamilyMember( "Son" ),
                              new FamilyMember( "Daughter" ) };
        Random generator = new Random();
        System.out.println( "Chores\tPerson" );
        System.out.println( "________________________________" );
        // Loop through all chores assigning them as we go.
        for( int j = 0; j < chores.length; ++j )
          int arrayIndex = generator.nextInt( fm.length );
          while( !chores[j].isAssigned() )
            while( !fm[arrayIndex].addChore( chores[j].getName() ) )
              arrayIndex = generator.nextInt( fm.length );
            chores[j].setAssigned( true );
          System.out.print( chores[j].getName() + "\t" );
          if( chores[j].getName().length() < 8 )
            System.out.print( "\t" );
          System.out.println( fm[arrayIndex].getName() );
        System.out.println( "________________________________" );
    }Enjoy,
    Manfred.

  • Problem with random number generation

    hey forum, i wonder if anyone can help me out with a small problem with my university coursework (yep its homework!!!)
    heres my problem, i am writing one of them 8 puzzle problems (the one based around sam lloyds 15 puzzler), i can successfully generate one random sequence of numbers with no duplicates, but whenever i call the random method again it keeps producing the same results
    heres the code
    in my main class file
    if(e.getSource() == randomButton) {
          new RandomPuzzle();
          System.out.println(random.randState);
          //startStateString = new RandomPuzzle();
    }heres my number generator class file
    import java.util.Random;
    import java.io.*;
    public class RandomPuzzle
         /** Base Random number generator */
        Random rn = new Random();
        /** Puzzle holder */
        byte b[];
        long number = 0;
        String randState = "";
        /** Default constructor */
        public RandomPuzzle() {
            rn.setSeed(number);
            b = new byte[9];
            randState = randomString();
        /** Provide range for generation */
        public int rand(int lo, int hi) {
            int n = hi - lo + 1;
            int i = rn.nextInt() % n;
            if (i < 0)
            i = -i;
            return lo + i;
        /** Set size for array */
        public int rand( int hi){
            int n = hi;
                return n;
        /** Check for duplicate values within the same configuration */
        boolean valueExists( byte value ) {
            int i = b.length;
            boolean exists = false;
            for( int j = 0; j < i; j++ ){
                if( b[j] == value )
                    exists = true;
            return exists;
        /** returns the actual string */
        public String randomString(int lo, int hi) {
            int n = rand( 9 );
            //boolean valueEntered = false;
            for (int i = 0; i < 9; i++) {
                boolean valueEntered = false;
                byte temp = (byte)rand('0', '8');
                while( valueEntered == false ) {
                    if( !valueExists( temp ) ) {
                         b[i] = temp;
                         valueEntered = true;
                    else
                        temp = (byte)rand('0', '8');
            return new String(b, 0);
        /** calls above function */
        public String randomString() {
            return randomString(0, 8);
    }i've tried for hours to work this out, but i am stumped. if anyone can point me in the right direction, maybe point out the problem code and give one or two tips i would be forever in your debt
    thanx in advance
    korbitz

    thanx for the help paulcw, but when i removed the seed code it done the same
    but i added this to my main class and now it works fine
    if(e.getSource() == randomButton) {
                   RandomPuzzle temp = new RandomPuzzle();
                   System.out.println(temp.randState);
                   //startStateString = new RandomPuzzle();
              }thanx again for your help

  • Need help with connecting file inputs to arrays

    In this assignment I have a program that will do the following: display a list of names inputed by the user in reverse order, display any names that begin with M or m, and display any names with 5 or more letters. This is all done with arrays.
    That was the fun part. The next part requires me to take the names from a Notepad file, them through the arrays and then output them to a second Notepad file.
    Here is the original program: (view in full screen so that the code doesn't get jumbled)
    import java.io.*;       //Imports the Java library
    class progB                    //Defines class
        public static void main (String[] arguments) throws IOException
            BufferedReader keyboard;                                  //<-
            InputStreamReader reader;                                 //  Allows the program to
            reader = new InputStreamReader (System.in);               //  read the the keyboard
            keyboard = new BufferedReader (reader);                  //<-
            String name;                 //Assigns the name variable which will be parsed into...
            int newnames;               //...the integer variable for the amount of names.
            int order = 0;              //The integer variable that will be used to set the array size
            String[] array;             //Dynamic array (empty)
            System.out.println (" How many names do you want to input?");   //This will get the number that will later define the array
            name = keyboard.readLine ();
            newnames = Integer.parseInt (name);                                         // Converts the String into the Integer variable
            array = new String [newnames];                                               //This defines the size of the array
            DataInput Imp = new DataInputStream (System.in);       //Allows data to be input into the array
            String temp;                                       
            int length;                                                                  //Defines the length of the array for a loop later on
                for (order = 0 ; order < newnames ; order++)                                //<-
                {                                                                           //  Takes the inputed names and
                    System.out.println (" Please input name ");                            //  gives them a number according to
                    temp = keyboard.readLine ();                                           //  the order they were inputed in
                    array [order] = temp;                                                  //<-
                for (order = newnames - 1 ; order >= 0 ; order--)                                //<-
                {                                                                                //  Outputs the names in the reverse 
                    System.out.print (" \n ");                                                   //  order that they were inputed
                    System.out.println (" Name " + order + " is " + array [order]);             //<-
                for (order = 0 ; order < newnames ; order++)                                  //<-
                    if (array [order].startsWith ("M") || array [order].startsWith ("m"))     //  Finds and outputs any and all
                    {                                                                         //  names that begin with M or m
                        System.out.print (" \n ");                                            //
                        System.out.println (array [order] + (" starts with M or m"));         //
                    }                                                                         //<-
                for (order = 0 ; order < newnames ; order++)                                            //<-
                    length = array [order].length ();                                                   //
                    if (length >= 5)                                                                    //  Finds and outputs names
                    {                                                                                  //  with 5 or more letters
                        System.out.print (" \n ");                                                      //
                        System.out.println ("Name " + array [order] + " have 5 or more letters ");      //<-
    }The notepad file contains the following names:
    jim
    laruie
    tim
    timothy
    manny
    joseph
    matty
    amanda
    I have tried various methods but the one thing that really gets me is the fact that i can't find a way to connect the names to the arrays. Opening the file with FileInputStream is easy enough but using the names and then outputing them is quite hard. (unless i'm thinking too hard and there really is a simple method)

    By "connect", do you just mean you want to put the names into an array?
    array[0] = "jim"
    array[1] = "laruie"
    and so on?
    That shouldn't be difficult at all, provided you know how to open a file for reading, and how to read a line of text from it. You can just read the line of text, put it in the array position you want, until the file is exhausted. Then open a file for writing, loop through the array, and write a line.
    What part of all that do you need help with?

  • Need some help with Random numbers.

    Hey,
    Im not sure why this is not working....
        public static void main(String[] args) {
        System.out.printf ("Enter n:\n");
        Scanner keyboard = new Scanner (System.in);
            int n1=0,
            n2=0,
            n3=0,
            n4=0,
            n5=0,
            n6=0,
            facevalue,
            x1,
            count = 0;
            double x = keyboard.nextDouble ();
            x1 = rollDie ();
            System.out.println(x1);
        while (count < x) {
            facevalue = 1+x1.nextInt (6);
            if (facevalue == 1) n1++;
            if (facevalue == 2) n2++;
            if (facevalue == 3) n3++;
            if (facevalue == 4) n4++;
            if (facevalue == 5) n5++;
            if (facevalue == 6) n6++;
            count += 1 ; }
        System.out.printf ("%d %d %d %d %d %d\n",n1,n2,n3,n4,n5,n6);
            int maxValue = n1;
            if (maxValue < n2)
                maxValue = n2;
            if (maxValue < n3)
                maxValue = n3;
            if (maxValue < n4)
                maxValue = n4;
            if (maxValue < n5)
                maxValue = n5;
            if (maxValue < n6)
                maxValue = n6;
        System.out.printf ("Max %d\n",maxValue);
        System.out.printf ("Avg %f\n",
        1/x*(n1*1+n2*2+n3*3+n4*4+n5*5+n6*6));
        public static int rollDie (){
            int x1 = (int) Math.random();
            System.out.println(x1);
            return x1;
    }The random number is always 0. Also there is an error at facevalue = 1+x1.nextInt (6); That says 'int cannot be dereferenced.' Please help! thanks!

    Also, this particular assignment seems to be a good time for you to learn about arrays. Look for a tutorial on java arrays. This will reduce your lines of code by 75%.
    What I mean is, you have 6 different variables to hold the total number of times each roll occurred. Instead, you could have a length-6 array:
      //declaring
      int[] tally = new int[6];
      //adding one to the tally
      int nextRoll = random.nextInt(6) + 1;
      tally[nextRoll-1]++;

  • Need Help with random numbers, please help

    Hi guys;
    I need your help for a school project. I need to generate a random number from 1.0 to 2.0. How would I do that?
    Regards,

    http://java.sun.com/j2se/1.3/docs/api/java/util/Random.html#nextFloat()

  • I need desperate help with Itunes for the SLVR

    I have a set playlist for Itunes to take songs from and put onto my phone when it is connected. That playlist has 56 songs, but when I click autofill, it only puts 31 songs down. As I add more songs to the playlist however, it only takes certain ones. For example, for every 7 songs I download into the playlist, it only takes 2 or 3. The phone has tons of space but I don't know, need desperate help, thanks in advance.

    i know i have the same problem the only one thing i have noticed that is consistant along with this problem is that songs that will not go on it are all of them have a higher bit rate than songs that do go on the phone but thats the only real thing i can notice so if someone can show me how to lower the bit rate if its possible that might be the miracle cure

  • Help: JSP Random Number Generator

    hello every one,
    Im trying to generate a random number using currentTimeMillis(), in Jsp, can you help me out and advice me how can this be done please.

    First you say you want a random number, then you say you want a unique one. Which is it?
    Random numbers do not normally guaruntee uniqueness.
    is there away i could use the currentTimeMillis(), What would you use it for? System.currentTimeMillis() is commonly used as a seed for a random number generator. The java.util.Random class uses it like that - take a look at that API link.
    Or if its a homework question state the exact requirement - I'm guessing here.

  • Help for random number generator???

    hi there can anyone how to make simple random number
    generator for slot machine , formula for chances in probability ,
    or simple random number generator for slot machine , thanks
    :)

    actualy the accurate RNG for slot machine ?? any idea?

  • Desperate help with putting video on ipod

    I had a movie on my ipod and after the new update came out, itunes took the movie off my ipod and said it can't be played on this ipod.Anyone know how to fix this?

    you need to convert the videos either to .mov or .mp4. either will be compatible for the ipod. you need to use 3rd party software not supported by apple.windows users have had trouble or success using this software.
    To use Videora iPod Convertor to convert movies for use on your iPod, consult these helpful links:
    To get started: http://www.videora.com/en-us/Converter/iPod/
    If you have questions: http://www.videora.com/en-us/Converter/guides.html
    If you have more questions, post them here: http://www.pspvideo9.com/forums/index.php?c=8
    Note that Videora iPod Convertor is a 3rd party program. If you need help with it, post your question there.
    GFF

  • Plz help me with random number generators

    cane someone help me write a program that generates 2 random numbers, generates a random operation(+,-,/,*) then ask you for answer, and checks to see if the answer is right, and if not it corrects it for you.
    thank you

    when i do the cases i did the addtion as the first case, and now all i get is addition
    import javax.swing.*;
    import java.text.*;
    import java.util.*;
    public class randomnumbers
         public static void main(String[] arg)
              String input;
              int answer;
              int choice=1;
              Random rand = new Random();
              int num1 = (int) (Math.random()*9+1);
              int num2 = (int) (Math.random()*9+1);
              switch(choice)
                   case 1:System.out.println("What is "+num1+"+"+num2);break;
                   case 2:System.out.println("What is "+num1*'*'*num2);break;
                   default:System.out.println("Illegel Operation");break;          
              input=JOptionPane.showInputDialog("What is the answer?");
              answer=Integer.parseInt(input);
    }

  • Hello from a new member and help with random images on refresh

    Hi All,
    I've just joined the forum. In fact I've really only just started to use Dreamweaver. I've covered a lot of ground in the last few weeks and
    have manage to set up a basic site using CSS for layout but now I've hit my first problem.
    On the index page of the site - http://www.hcadesign.co.uk/ there is a large main image which I would like to change each time someone
    visits the site or hits refresh. I've hunted around and found lots of scripts, all using java, that seem to do just this but I'm not having any
    luck getting them to work.
    My pages code is as follows -
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Humphrey Cook Associates - Architects - Interior Designers - Project Managers</title>
    <link href="styles/hca_styles.css" rel="stylesheet" type="text/css" media="screen" />
    </head>
    <body>
    <div id="wrapper">
      <div id="header"><img src="images/header.gif" width="800" height="100" alt="hca_header" /></div>
      <div id="menu">
        <ul>
          <li>About Us</li>
          <li>Residential </li>
          <li>Special Needs Housing</li>
          <li>Hotels</li>
          <li>Conservation</li>
          <li>Interiors</li>
          <li>Offices</li>
          <li>Sustainability</li>
          <li>Commercial</li>
          <li>News</li>
          <li>Contact</li>
        </ul>
      </div>
      <div id="main_image"><img src="images/haydock_atrium_420x300.jpg" width="420" height="300" alt="haydock_atrium" />
      </div>
      <div id="menu_right">
        <h3>Latest News</h3>
        <p>Planning permision finally granted for the proposed 'Villa De France'</p>
        <div id="news_image_01">
          <p><img src="images/news_villa_de_france_90x50.jpg" alt="villa_de_france" width="90" height="50" /></p>
        </div>
        <p>Application submitted for new 30 storey hotel with retail in Tower Hamlets</p>
        <div id="news_image_02"><img src="images/news_alie_St_90x50.jpg" width="90" height="50" alt="alie_street" /></div>
      </div>
      <div id="spacer"></div>
      <div id="bottom_left"><img src="images/riba_logo_127x67.gif" width="127" height="67" alt="riba_logo" /></div>
      <div id="bottom_thumb_01"><img src="images/thumb_beckton_95x67.jpg" width="95" height="67" alt="beckton" /></div>
      <div id="bottom_thumb_02"><img src="images/thumb_edgeworth_link_95x67.jpg" width="95" height="67" alt="edgeworth" /></div>
      <div id="bottom_thumb_03"><img src="images/thumb_tov_bathroom_95x67.jpg" width="95" height="67" alt="haydock" /></div>
      <div id="bottom_thumb_04"><img src="images/thumb_edgeworth_interiors_portrait_95x67.jpg" width="95" height="67" alt="the_old_vicarage" /></div>
    <div id="bottom_right">
      <h1>Architects</h1>
      <h1>Interior Designers</h1>
      <h1>Project Managers</h1>
    </div>
      <div id="footer"></div>
    </div>
    </body>
    </html>
    I've highlighted where the image to be rotated is in red.
    The scripts I've found have generally involved putting something in the <head>, something where the image is to be (but I wasn't sure if it should be
    within the div tag or after img src or what?) and also a seperate *.js file stored in the root directory.
    Anyway I'm not getting anywhere and need some help as I really don't know what I'm doing with javascript.
    Cheers

    Hi and Welcome to the DW Forums. 
    For the sake of clarity, Java is not the same thing as JavaScript. 2 entirely different programming languages.
    Copy and paste the following code into a new, blank HTML page.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Random Banner</title>
    <script type="text/javascript">
    <!--//Random Banner image on Page Reload 
    //store the images in arrays below.
    //First banner is always image [0].
    //If you add more banners images, change the array count (4).
    images = new Array(4);
    images[0] = "<a href='http://www.example.com'>
    <img src='path/first-image.jpg' width=' ' height=' ' alt='some-description' /> </a>";
    images[1] = "<a href='http://www.example.com'>
    <img src='path/second-image.jpg' width=' ' height=' ' alt='some-description' /> </a>";
    images[2] = "<a href='http://www.example.com'>
    <img src='path/third-image.jpg' width=' ' height=' ' alt='some-description'  </a>";
    images[3] = "<a href='http://www.example.com'>
    <img src='path/fourth-image.jpg' width=' ' height=' ' alt='some-description'  </a>";
    index = Math.floor(Math.random() * images.length);
    document.write(images[index]);
    //done
    // -->
    </script>
    </head>
    <body>
    <h1>Random Banner on Page Load.</h1>
    <p>The more images you have in your array, the more random it will seem.</p>
    <p>Change the URLs from example.com to your your own site pages.</p>
    <p>Change path/image to images in your local site folder.</p>
    </body>
    </html>
    Good luck with your project,
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists
    http://alt-web.com/
    http://twitter.com/altweb
    http://alt-web-design.blogspot.com/

  • Really need help with re-number rows

    I am trying to update the Precedence value for each row based on its order in the ORDER BY clause. What I am doing is I allow users to insert rows above or below other rows. This is done by adding 0.5 or -0.5 to the PRECEDANCE value of the row they are inserting above or blow. Once this is done I need to update all rows with a new hole number PRECIDANCE value getting ready for the next insert.
    Any help would be great, even an entirely different way!
    UPDATE
    TABLE_A TBL_A
    SET
    TBL_A.PRECEDENCE = (ROWNUM * 10)
    WHERE
    TBL_A.EMP_ID in
    select
    EMP_ID,
    PRECEDENCE
    from(
    select
    TBL_A.EMP_ID,
    TBL_A.PRECEDENCE
    from
    TABLE_A TBL_A
    where
    TBL_A.OTHER_ID = :THIS_ID
    order by
    2,
    1     
    )

    On average, though, Andrew's procedure will update half the rows in the table on every insert (assuming that your inserts occur between two rows at random). If there are a lot of rows in the table or if there are a lot of inserts, this may not scale particularly well. It may also cause problems if you have an optimistic locking mechanism in place to handle multiple users updating the table simultaneously.
    I'd still do something like
    CREATE OR REPLACE PROCEDURE insert_after( p_prior_precedence IN NUMBER,
                                              p_row              IN <<table name>>%rowtype )
    AS
      l_next_precedence NUMBER;
    BEGIN
      SELECT MIN(precedence)
        INTO l_next_precedence
        FROM <<table>>
       WHERE precedence > p_prior_precedence;
      p_row.precedence := (p_prior_preceddence + l_next_precedence) / 2;
      INSERT INTO <<table>> VALUES p_row;
    END;This way, you don't have to update any rows when you do an insert. You don't get integer precedence values, but this strikes me as a reasonable trade-off. If you want to re-number things either at query time
    SELECT <<columns>>
           RANK() OVER (PARTITION BY <<something>> ORDER BY precedence) pretty_precedence
      FROM <table name>>or as a nightly job, that would work.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

Maybe you are looking for