Problem with Do-While Loop in a Binary Search

The idea of the program is to randomly generate 10 integers, store them in an array then use a binary search to find the values at each position of the array in 10 or less steps.
My problem is that the do-while loopisn't doing what it should be and I can't see the problem :S
Thanks in advance.
Se�n.
int counter=0, guess=500, MIN=0, MAX=0;
int arr[] = new int[10];
          for(int i=0; i<10; i++) {
      int ranNum= ( (int)(Math.random()*1000)+1 );
      arr=ranNum;
     System.out.println(ranNum);
     for(int j=0; j<10; j++) {
          do{
               if(guess>arr[j]){
                    guess=MAX;
                    guess=guess/2;
               else if(guess<arr[j]){
                    guess=MIN;
                    MAX=MIN*2;
guess=((MAX-MIN)/2)+MIN;
               else
                    guess=arr[j];
}while(guess!=arr[j]);
          System.out.println("The number at position "+j+" in the array is :"+arr[j]);
//resets the values each time the do-while loops breaks
          MIN=0;
          MAX=0;
          guess=500;

Looks toe like MAX and MIN are always going to be zero.

Similar Messages

  • Problems with a while loop within a method... (please help so I can sleep)

    Crud, I keep getting the wrong outputs for the reverseArray. I keep getting "9 7 5 7 9" instead of "9 7 5 3 1". Can you guys figure it out? T.I.A (been trying to figure this prog out for quite some time now)
    * AWT Sample application
    * @author Weili Guan
    * @version 1999999999.2541a 04/02/26
    public class ArrayMethods{
       private static int counter, counter2, ndx, checker, sum, a, size, zero;
       private static int length;
       private static int [] output2, output3, reverse, array;
       private static double output;
       private static double dblsum, dblchecker, average;
       public static void main(String[] args) {
          //int
          //int [] reverse;
          System.out.println("Testing with array with the values [1,3,5,7,9]");
          size = 5;
          array = new int [size];
          reverse = new int [size];
          array[0] = 1;
          array[1] = 3;
          array[2] = 5;
          array[3] = 7;
          array[4] = 9;
          System.out.println("Testing with sumArray...");
          output = sumArray(array);
          System.out.println("Sum of the array: " + sum);
          System.out.println();
          System.out.println("Testing with countArray...");
          output = countArray(array);
          System.out.println("Sum of the elements : " + checker);
          System.out.println();
          System.out.println("Testing with averageArray...");
          output = averageArray(array);
          System.out.println("The average of the array : " + average);
          System.out.println();
          System.out.println("Testing with reverseArray...");
          output2 = reverseArray(array);
          output3 = reverseArray(reverse);
          //System.out.print(reverse[4]);
          System.out.print("The reverse of the array : ");
          for(ndx = 0; ndx < array.length; ndx++){
             System.out.print(reverse[ndx] + " ");
       private ArrayMethods(){
       public static int sumArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if (array[ndx] > 0){
                checker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                sum += array[ndx];
                ndx++;
             return sum;
          else{
             sum = 0;
             return sum;
        /*Computes the sum of the elements of an int array. A null input, or a
        zero-length array are summed to zero.
        Parameters:
            array - an array of ints to be summed.
        Returns:
            The sum of the elements.*/
       public static int countArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if(array[ndx] > 0 && array[ndx] != 0){
                checker++;
             counter++;
          return checker;
        /*Computes the count of elements in an int array. The count of a
        null reference is taken to be zero.
        Parameters:
            array - an array of ints to be counted.
        Returns:
            The count of the elements.*/
       public static double averageArray(int[] array){
          dblchecker = 0;
          ndx = 0;
          counter = 0;
          dblsum = 0;
          while(counter < array.length){
             if(array[ndx] > 0){
                dblchecker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                dblsum += array[ndx];
                ndx++;
             average = dblsum / dblchecker;
             return (int) average;
          else{
             average = 0;
             return average;
        /*Computes the average of the elements of an int array. A null input,
        or a zero-length array are averaged to zero.
        Parameters:
            array - an array of ints to be averaged.
        Returns:
            The average of the elements.*/
       public static int[] reverseArray(int[] array){
          ndx = 0;
          counter = 0;
          counter2 = 0;
          if(array.length == 0){
             array[0] = 0;
             return array;
          else{
                //reverse = array;
             while(ndx <= size - 1){
                   reverse[ndx] = array[4 - counter];
                   counter++;
                   ndx++;
                   System.out.print("H ");
          return reverse;
        /*Returns a new array with the same elements as the input array, but
        in reversed order. In the event the input is a null reference, a
        null reference is returned. In the event the input is a zero-length array,
        the same reference is returned, rather than a new one.
        Parameters:
            array - an array of ints to be reversed.
        Returns:
            A reference to the new array.*/
    }

    What was the original question? I thought it was
    getting the desired output, " 9 7 5 3 1."
    He didn't ask for improving the while loop or the
    reverseArray method, did he?
    By removing "output3 = reverseArray(reverse):," you
    get the desired output.Okay, cranky-pants. Your solution provides the OP with the desired output. However, it only addresses the symptom rather than the underlying problem. If you'd bother yourself to look at the overall design, you might see that hard-coding magic numbers and returning static arrays as the result of reversing an array passed as an argument probably isn't such a great idea. That's why I attempted to help by providing a complete, working example of a method that "reverses" an int[].
    Removing everything and providing "System.out.println("9 7 5 3 1");" gets him the desired output as well, but (like your solution) does nothing to address the logic problems inherent in the method itself and the class as a whole.

  • Problem with a while loop.

    I'm very new to java so please bear with me!!!
    This is my code:
    import java.io.*;
    public class IfExample2
        public static void main (String[] args) throws IOException
         // Read in a number
         BufferedReader br = new BufferedReader(
                         new InputStreamReader (System.in));
         System.out.print ("Enter a number between 0 and 10 inclusive: ");
         String temp = br.readLine();
         double x = Double.parseDouble(temp);
         // check user input
         if (x > 10)
             System.out.println("The number you entered is too high");
              System.out.println("Please re-enter the number");
         else if (x < 0)
             System.out.println("The number you entered is too low");
              System.out.println("Please re-enter the number");
         else
             System.out.println("The number you entered is " + x);
    }Basically I want, if the number entered is too high or too low I want it to ask the user to re-enter the number, I want to use a while loop but I'm not sure where or how to use it, please help!

    while ( condition ) {
        // stuff here
    }More on while: [http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html]
    Edited by: oscarjustesen on Oct 7, 2008 5:40 PM
    Edited - fixed link

  • Having problems with do.while loops

    import javax.swing.*;
    import java.text.DecimalFormat;
    public class Assign32437 {
      public static void main(String[] args) {  // METHOD
       String strCost, strResVal, strUseLife, strDepre;
       double useLife = 0, deprec=0, Cost=0,resVal=0,accumulatedDepreciation = 0;
       double yearlyDepreciation = 0,Carryingvalue = 0;
       int repeat = 0, year = 0;
       DecimalFormat myFormat = new DecimalFormat("$0.00");
       JTextArea outputTextArea= new JTextArea();
         outputTextArea.append("\t\t Depreciation Schedule\n\n" + " End of year\t"
                               + "Cost\t" + "Yearly deprecation\t" +
                               "Accumulated Depreciation\t" + "Carrying value\n");
       do{   //ENTER COST OF ITEM
           strCost = JOptionPane.showInputDialog("Enter cost (>0):");
           Cost = Double.parseDouble(strCost);
        while (Cost < 0);
        do {       //ENTER ESTIMATED VALUE
           strResVal = JOptionPane.showInputDialog(
               "Enter residual value(>=0 and <cost:)");
           resVal = Double.parseDouble(strResVal);
        while (resVal < 0 || resVal > Cost);
        do {       //ENTER USEFUL LIFE
           strUseLife = JOptionPane.showInputDialog("Enter useful life(>0):");
           useLife = Double.parseDouble(strUseLife);
        while (useLife < 0);
        for (year = 0; year <= useLife; year++)
           deprec = (Cost - resVal) / (useLife);
           accumulatedDepreciation = (yearlyDepreciation * year); //CALCULATIONS
           Carryingvalue = (Cost - accumulatedDepreciation);
           outputTextArea.append(year + "\t" + Cost + "\t" + deprec + "\t" +
           accumulatedDepreciation + "\t" + Carryingvalue + "\n");
         JOptionPane.showMessageDialog(null, outputTextArea);
         repeat = JOptionPane.showConfirmDialog(null, "DO YOU WANT TO CONTINUE?\n",
                                                "Continue?",
                                                JOptionPane.YES_NO_OPTION);
         while(repeat==0);
       System.exit(0);
          }

    no error msgs. im not asking someone to do it for me. just looking for some pointers...
    when i run my code i am not being asked for more then one year ie: no loop is occuring. so i enter information and on my outputTextArea.append(year + "\t" + Cost + "\t" + deprec + "\t" +
           accumulatedDepreciation + "\t" + Carryingvalue + "\n"); displays one years totals like 30 times

  • What's wrong with this while loop?

    Hi, folks. for the code fragment blow, resultSetArray holds two objects of type ResultSet. From those println statement, i can see the whole while loop(the most outter one) process goes alrite the first time right from begining to the end. However, when variable j increases from 0 to 1, the code stops executing at the the line while(rs.next). I just couldnt figure out what causes the problem while i've been fighting with it for several hours. Could someone plz throw me some lights? With your help, i could possibly go to bed before sun rises...
            while(j<resultSetArray.length)
              //for(int j=0; j<resultSetArray.length; j++)
    System.out.println("show me j is called twice " + j);
                   ResultSet rs = resultSetArray[j];
    System.out.println("the converting rs object is called twice and it is not null " + rs);
                  int numWantedColumns = wantedColumnNames.size();
                  //if it's about go or single trip
                  if(j==0 && rs != null)
                      go = new Element("Go");
                       //go.setText("go");
                       //result.addContent(go);
                  //if it's about return trip
                  else if(j==1 && rs != null)
                      back = new Element("Back");
                       //back.setText("back");
                       //result.addContent(back);
                  if(rs!= null)
    System.out.println("this hell is called twice coz it's not null");
                   while(rs.next())
    System.out.println("what about here?");
                        Element flightInfo = new Element("FlightInfo");
         System.out.println("while rs.next() is called");
                        for (int i = 0; i < numWantedColumns; i++)
                           String columnName   = (String)wantedColumnNames.get(i);
         System.out.println("column name is " + columnName);
                           String value = rs.getString(columnName);
          System.out.println("column value is " + value);
                           flightInfo.addContent(new Element(columnName).setText(value));
                        if(j==0)
                           go.addContent(flightInfo);
                        else if(j==1)
                             back.addContent(flightInfo);
                   else if(rs == null)
                        break;
                   j++;
             }

    i've got the problem sort out, eventually. there was actually nothing wrong with the while loop. it was caused by a typo in databse, instead of having Brisbane, i typed Bisbane. The single letter r cost me more than 6 hours to figure it out. it was such a painful feeling while i realized i made a such stupid mistake.
    by the way, as jnw777 mentioned, output rs.next() info instead of the test line. i did try it, however i didnt realize even System.out.println(rs.next()) would cause the cursor move down one row from its current position. so, plus the original while(rs.next()) statement, it was moving the cursor two rows down at a time! And i just couldnt think of this caused me the fact i was only getting the even number row of the ResultSet while i was sniffing the bug from a class with 700+ lines of code. I was so excited and just couldnt stop yelling at the moment i got over it! That was a damn execiting moment...
    now, i am wondering if anyone in this wonderland would like to share his/her stories.

  • Why the execution time increases with a while loop, but not with "Run continuously" ?

    Hi all,
    I have a serious time problem that I don't know how to solve because I don't know exactly where it comes from.
    I command two RF switches via a DAQ card (NI USB-6008). Only one position at the same time can be selected on each switch. Basically, the VI created for this functionnality (by a co-worker) resets all the DAQ outputs, and then activates the desired ones. It has three inputs, two simp0le string controls, and an array of cluster, which contains the list of all the outputs and some informations to know what is connected (specific to my application).
    I use this VI in a complex application, and I get some problems with the execution time, which increased each time I callled the VI, so I made a test VI (TimeTesting.vi) to figure out where the problem came from. In this special VI I record the execution time in a csv file to analyse then with excel.
    After several tests, I found that if I run this test VI with the while loop, the execution time increases at each cycle, but if I remove the while loop and use the "Run continuously" funtionnality, the execution time remains the same. In my top level application I have while loops and events, and so the execution time increases too.
    Could someone explain me why the execution time increases, and how can I avoid that? I attached my test VI and the necessary subVIs, as well as a picture of a graph which shows the execution time with a while loop and with the "run continuously".
    Thanks a lot for your help!
    Solved!
    Go to Solution.
    Attachments:
    TimeTesting.zip ‏70 KB
    Graph.PNG ‏20 KB

    jul7290 wrote:
    Thank you very much for your help! I added the "Clear task" vi and now it works properly.
    If you are still using the RUn Continuously you should stop. That is meant strictly for debugging. In fact, I can't even tell you the last time I ever used it. If you want your code to repeat you should use loops and control the behavior of the code.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • Slow performance of application with 2 while-loops

    I made an application with one while-loop addressing several FP devices which runs as expected in a FP-2015. Loop time is 100 ms.
    If I add another while-loop with a timer, the performance is very slow. How come?

    I tried to do a simular thing, but I did not notice a performance decrease. However it might be possible that this happens. For example, if you are calling a time critical vi in the second while loop, it will lock all other processes until it is finished. Or maybe you are calling a shared resource (allocate an array, access to a file, using a mutex) that the other loop holds. Until the shared resource is released the first while loop must wait before it can access that resource (memory, file, etc.).
    Without looking at the source code it will be hard to say what is causing it. I recommend to remove part by part subVI's from the second loop, to debug where the problem exists. If you want I can have a look at the code, please reply to this thread.
    ErikvH
    A
    pplications Engineering
    National Instruments
    Attachments:
    Digital_Output.vi ‏56 KB

  • Compilation problem with templates while using option -m64

    Hi,
    I have compilation problem with template while using option -m64.
    No problem while using option -m32.
    @ uname -a
    SunOS snt5010 5.10 Generic_127111-11 sun4v sparc SUNW,SPARC-Enterprise-T5220
    $ CC -V
    CC: Sun C++ 5.9 SunOS_sparc Patch 124863-01 2007/07/25
    Here is some C++ program
    ############# foo5.cpp #############
    template <typename T, T N, unsigned long S = sizeof(T) * 8>
    struct static_number_of_ones
    static const T m_value = static_number_of_ones<T, N, S - 1>::m_value >> 1;
    static const unsigned long m_count = static_number_of_ones<T, N, S - 1>::m_count + (static_number_of_ones<T, N, S - 1>::m_value & 0x1);
    template <typename T, T N>
    struct static_number_of_ones<T, N, 0>
    static const T m_value = N;
    static const unsigned long m_count = 0;
    template <typename T, T N>
    struct static_is_power_of_2
    static const bool m_result = (static_number_of_ones<T,N>::m_count == 1);
    template <unsigned long N>
    struct static_number_is_power_of_2
    static const bool m_result = (static_number_of_ones<unsigned long, N>::m_count == 1);
    int main(int argc)
    int ret = 0;
    if (argc > 1)
    ret += static_is_power_of_2<unsigned short, 16>::m_result;
    ret += static_is_power_of_2<unsigned int, 16>::m_result;
    ret += static_is_power_of_2<unsigned long, 16>::m_result;
    ret += static_number_is_power_of_2<16>::m_result;
    else
    ret += static_is_power_of_2<unsigned short, 17>::m_result;
    ret += static_is_power_of_2<unsigned int, 17>::m_result;
    ret += static_is_power_of_2<unsigned long, 17>::m_result;
    ret += static_number_is_power_of_2<17>::m_result;
    return ret;
    Compiation:
    @ CC -m32 foo5.cpp
    // No problem
    @ CC -m64 foo5.cpp
    "foo5.cpp", line 20: Error: An integer constant expression is required here.
    "foo5.cpp", line 36: Where: While specializing "static_is_power_of_2<unsigned long, 16>".
    "foo5.cpp", line 36: Where: Specialized in non-template code.
    "foo5.cpp", line 26: Error: An integer constant expression is required here.
    "foo5.cpp", line 37: Where: While specializing "static_number_is_power_of_2<16>".
    "foo5.cpp", line 37: Where: Specialized in non-template code.
    "foo5.cpp", line 20: Error: An integer constant expression is required here.
    "foo5.cpp", line 43: Where: While specializing "static_is_power_of_2<unsigned long, 17>".
    "foo5.cpp", line 43: Where: Specialized in non-template code.
    "foo5.cpp", line 26: Error: An integer constant expression is required here.
    "foo5.cpp", line 44: Where: While specializing "static_number_is_power_of_2<17>".
    "foo5.cpp", line 44: Where: Specialized in non-template code.
    4 Error(s) detected.
    Predefined macro:
    @ CC -m32 -xdumpmacros=defs foo5.cpp | & tee log32
    @ CC -m64 -xdumpmacros=defs foo5.cpp | & tee log64
    @ diff log32 log64
    7c7
    < #define __TIME__ "09:24:58"
    #define __TIME__ "09:25:38"20c20
    < #define __sparcv8plus 1
    #define __sparcv9 1[snipped]
    =========================
    What is wrong?
    Thanks,
    Alex Vinokur

    Bug 6749491 has been filed for this problem. It will be visible at [http://bugs.sun.com] in a day or two.
    If you have a service contract with Sun, you can ask to have this bug's priority raised, and get a pre-release version of a compiler patch that fixes the problem.
    Otherwise, you can check for new patches from time to time at
    [http://developers.sun.com/sunstudio/downloads/patches/]
    and see whether this bug is listed as fixed.

  • Hello. I have problem here can someone plz help. I have usb of 32 gb but i have problem with it while i was trying to partition of it and it fails and my usb disappear from finder and desktop i have tried every possible thing but nothing  works .

    Hello. I have problem here can someone plz help. I have usb of 32 gb but i have problem with it while i was trying to partition of it and it fails and my usb disappear from finder and desktop i have tried every possible thing but nothing  works .

    Yea i tried in disk utility and its got faiiled and the partitation has deleted and when i tried  to replug the  usb  msg show up by saying  usb not compaitnle. With this mac  and  take me to disk utility  and thanks for replying

  • Can anyone please help me, I'm having problems with sound while watching video clips using flash player using Internet Explorer\

    Can anyone please help me, I'm having problems with sound while watching video clips using flash player & Internet Explorer

    There's a good chance that this is a known issue.  We'll have a Flash Player 18 beta later this week that should resolve this at http://www.adobe.com/go/flashplayerbeta/

  • The demand of my application is that i can not replace for loop with a while loop.because i need fixed number of iterations and as far as i know fixed iterations could be only with possible with the for loop.

    the demand of my application is that i can not replace for loop with a while loop.because i need fixed number of iterations and as far as i know fixed iterations could be only with possible with the for loop.
    your recommended second option that i could add true/false case.
    this true/false case must be inside the for loop or outside the for loop?if this case is inside the for
    loop, how can i send stop command from outer while
    loop?
    more over do you have any example for this please?
    thanks"

    You can execute a fixed number of iterations using a while loop by comparing the iteration count to the number of iterations you want and wiring the output of that comparison (e.g. Less Than or Equal To) to the continue (or stop) terminal of your while loop. Which comparison you use depends on personal preference, where you wire the desired count and the interation count, and whether you're using the while loop as Continue if True or Stop if True.
    Ben gave you step-by-step instructions in response to your previous question. Look here for Ben's response.
    Ben's response looks pretty good and detailed to me. It certa
    inly deserved better than a 1-star rating.

  • Problem with unwanted endless loop while reading a file

    Hi everyone,
    i got stuck with a class, that reads all words out of an input file, counts each file's frequency and prints out a list with words and frequency.
    Everything works fine as long as i use a In.read() method included in a example class provided by the book i use to learn java. But this method will not be allowed to use in the exam, even if the whole lecture at uni based on it. Well, not that much a problem, if i would be able to replace it by a FileReader or something like this.
    Problem: The test file (input.txt) contains a phrase like "This is a test text to count the words included in the test text". Shoul return all unique words and their frequency. As my pc crashed everytime i started the class, i found out that my failure has to come from the readWord method. It reads the first word in an endless loop (which seems to be the reason for the crashs) and is not willing to continue reading the next word after it returned the first to the main method. Instead it resets and starts from the beginning. I stripped of any additional processing methods and included a "system.out.println()" in order to narrow down the failure.
    I really don't understand this, because read() reads character after character and it is added to the buffer as planed and i don't see any reason why it resets to 0. I can use the same code (apart from the file reader and exception handling stuff and the "!= -1" check) with the In.java-class and it works.
    Here comes the code. Any help would be greatly appreciated.
    Greg
    import java.io.*;
    public class WordCount {
          * @param args
         public static void main(String[] args) throws IOException {
              //reads first word out of the input file
              String w = readWord();
              while(w != null){
                   //test output to verify anything is read
                   System.out.println(w);
                   //next word to read
                   w = readWord();
              //close input stream
              System.in.close();
         static String readWord() throws IOException{
              FileReader eingabestrom = new FileReader("input.txt");
              StringBuffer word = new StringBuffer();
              int gelesen;
              /*read first character
               * -1 if no text in the input file. In this case,
               * both while loops are skipped and "null" is returned
              do gelesen = eingabestrom.read();
              //skip blanks
              while(gelesen != -1 && !Character.isLetter( (char) gelesen));
              //read all characters of a word and append it to the "word" stringbuffer
              while(gelesen != -1 && Character.isLetter( (char) gelesen)){
                   word.append( (char) gelesen);
                   gelesen = eingabestrom.read();
              //if read was successful, convert buffer to string and return it to main.
              if(word.length() > 0){
                   return word.toString();
              //if read was unsuccessful, return null
              }else{
                   return null;
    }

    Thank you! :)
    Works perfectly, i do understand most of it and i discovered the little mistake that prevented it from starting ;)
    Set<Map.Entry><String,Integer>> set = tm.entrySet();Needs less than half the code i used before :)
    Thx again
    Greg

  • I am facing lots of problems with security while using Mozilla. How can I send you a detailed report for this?

    I am getting redirected to unknown sites whenever I open any site while using mozilla. Initially I thought that there is a problem with my device, but then I realized that this happens only when using mozilla, not with other browsers like chrome, IE, or opera.
    These sites are mainly having the message 'Ad by ShopDrop'..
    I am pasting below links to few sites to which I get redirected to
    http://offers.bycontext<i></i>.com/scjs/tb/ctxjs/index<i></i>.php?kw2=www.espncricinfo<i></i>.com&affid=1151&subaff_id=725_724&intformat=roll&nextpage=http%3A%2F%2Fwww.espncricinfo<i></i>.com%2F&ch=421&sbrand=ShopDrop&folder=v4.19&typrd=ctx&cu=32929&country=IN&original_country=IN
    http://add0n<i></i>.com/fastest-gmail.html?v=0.1.6&p=0.1.5&type=upgrade

    hello, you have various malicious addons present. please perform all these steps:
    # [[Reset Firefox – easily fix most problems|reset firefox]] (this will keep your bookmarks and passwords)
    # afterwards go to the firefox menu ≡ > addons > extensions and in case there are still extensions listed there, disable them.
    # finally run a full scan of your system with different security tools like the [http://www.malwarebytes.org/products/malwarebytes_free free version of malwarebytes] and [http://www.bleepingcomputer.com/download/adwcleaner/ adwcleaner] to make sure that adware isn't present in other places of your system as well.
    [[Troubleshoot Firefox issues caused by malware]]

  • Problem with non-stop looping

    This file has been supposedly changed from As2 to As3. It seems as if it used to stop when I first got it. But the links didn't work. When I followed troubleshooting protocols, it started looping non-stop.
    Please help. I can't seem to attach the flv and the action script files. All I get from the output window is "Fonts should be embedded for any text that may be edited at runtime, other than text with the "Use Device Fonts" setting. Use the Text > Font Embedding command to embed fonts."
    Please help. I paid a coder to switch the file from as2 to as3 and this is what he gave me...

    contact that coder and let them know the problem.  if it's a problem with their code, they should fix it without charge.

  • Query with a WHILE loop

    DECLARE
    @databasename AS
    NVARCHAR(128);
    SET
    @databasename =
    (SELECT
    MIN(name)
    FROM sys.databases
    WHERE
    name NOT
    IN    ('master',
    'model',
    'msdb', 'tempdb'));
     WHILE
    @databasename IS
    NOT NULL BEGIN
    PRINT @databasename;
    SET @databasename
    = (SELECT
    MIN(name)
    FROM sys.databases
            WHERE
    name NOT
    IN     ('master',
    'model',
    'msdb', 'tempdb')
            AND
    name >
    @databasename); END
    Databases
    A
    B
    C
    D
    I have question related to the above SQL statement, forgive me as I am unfamiliar with WHILE loops.
    I understand that the query above finds the minimum database name, prints the value then finds the next database greater than the minimum.
    What happens when it loops occurs,  I know it prints the database name of the one it has found.  In the example above it will be B.  Will the @databasename be then set to B and the following query will be run so the @databasename will then be
    set to C?
     SELECT
    MIN(name)
    FROM sys.databases
            WHERE
    name NOT
    IN     ('master',
    'model',
    'msdb', 'tempdb')
            AND
    name >
    @databasename);

    Yes. You run this query:
    SET  @databasename =
       (SELECT MIN(name)
        FROM   sys.databases
        WHERE  name NOT IN    ('master','model', 'msdb', 'tempdb'));
    This gives you the first user database, alphabetically according to your system database. The WHERE clause filters out the system databases.
    Then in the WHILE loop you do the same, with one condition added:
         AND name > @databasename
    So this gives the next user database alphabetically. But if there is no further database, the query returns NULL, and the condition in the WHILE statement will evaluate to FALSE, and the loop will terminate.
    Erland Sommarskog, SQL Server MVP, [email protected]

Maybe you are looking for

  • Problem with ABAP proxies - HTTP connection to R/3 is not working

    Hi guys! I'm setting up a connection from XI to R/3 , because I'm using proxy objects. Our DEV is working fine. Now I have moved the objects to QA and since the HTTP connection is not there, I need to set it up. I have created a service user on R/3,

  • Number range issue

    Hi, I am trying to create idoc wherein I am getting error : Runtime Error          SAPSQL_ARRAY_INSERT_DUPREC Exception              CX_SY_OPEN_SQL_DB I checked the details and error is at: INSERT EDID4 FROM TABLE LIST_CONTAINER_CREATE I checked the

  • How to use function module 'MC_POPUP_TO_MARK_VALUES' ?

    Hai, I  used   CALL FUNCTION  'MC_POPUP_TO_MARK_VALUES'   to delete duplicates in the F4 help  but    in my program ,When we press F4 help , radio buttons are appearing in the F4 help window. How to avoid that ? Or is there any other function module

  • IPad 3G: Verizon or ATT better Queens NY?

    I'm buying an IPad for my friend who doesn't have broadband at home. He lives in Nassau County, just east of the Queens border. Have tried researching Verizon vs. ATT online, but not much info. Do know ATT is supposed to be faster but less reliable.

  • Opening FPM Application in a seperate Model Window

    Dear Experts, I have a FPM Application which i need to open in new Window in my Webdynpro Application. As of now I am using the URL of the Application to open it as an external WIndow, this causes some problem while refreshing the main Webdynrpo view