Help with a while loop condition

I'm trying to write to a File. I ask the user for input, then I enter a while loop and test the condition. The loop works, but it won't stop. I've tried everything. Here is my code please help!!
thanks
inputline = keyboard.readLine();//read the keyboard
try{
while( inputline != null ){
DiskOut.println( inputline );
DiskOut.flush();
inputline = keyboard.readLine();//read the keyboard again
}//end while
}//end try
catch (IOException e) { 
e.printStackTrace();
}//end catch
also i've tried these while loop conditions:
while(inputline != "\n" || inputline != "\r") and the sort

while(inputline != "\n" || inputline != "\r")The condition
X!=Y OR X!=Z (given Y != Z)
is always true. X will always not be equal to at least one of the values. So you'll want to use:
while(!inputline.equals("\n") && !inputline.equals("\r"))In other words, "while inputline is not equal to either of them". Note the use of && instead of ||.
If "keyboard" is simply a BufferedReader on top of System.in (and not your own class), the trailing line feeds and carriage returns won't even be in the string returned by readLine(). Your best bet is this:
while(null != inputline && 0 != inputline.length())Make sure you type the two parts of that AND condition in the order above. If for whatever reason there are trailing \r and \n on the strings, you'll want to accomodate for platforms that may include both characters.
// trim the trailing newline characters
while(inputline.endsWith("\r") ||
      inputline.endsWith("\n")) {
   inputline = inputline.substring(0,inputline.length()-1);
// or maybe this will work if you don't mind losing
//  the whitespace at the beginning of the string:
inputline = inputline.trim();Hope that helps somewhat.

Similar Messages

  • Help with "Do While" loop :D

    Why wont my code exit when dw is equal to "W" or "D" ?
    import java.io.*;
    public class mess
         public static void main(String args[]) throws IOException
              InputStreamReader isr = new InputStreamReader(System.in);
              BufferedReader keyb = new BufferedReader(isr);
              String dw = "";
                   do
                      System.out.println("Type in Deposit or withdrawal [D/W]: ");
                      dw = keyb.readLine();
                      dw = dw.toUpperCase();
                      System.out.println(dw);
                      if (dw.equals("D"))
                           System.out.println("Exit loop with D");
                        else if (dw.equals("W"))
                             System.out.print("Exit loop with W");
                        else
                        System.out.println("Error- Invaild input");
                } while (!dw.equals("D") || (!dw.equals("W")));     //condition for exit
    }

    You should use
      while (!dw.equals("D")  && (!dw.equals("W"))); //condition for exit

  • Help with do while loop

      This program that reads a character representing a geometrical
      figure, then asks the user to enter the required data (ex. Radius for
      a circle, length and height for a rectangle, etc.  ...) .
      The program should then print the area and circumference.   Figures are: circle(c), square(s), rectangle(R), triangle (t).
      The program should repeat until a figure with area <10 are read
       import javax.swing.JOptionPane; // program uses class JOptionPane
        public class Sh7q6
       // main method begins execution of Java application
           public static void main( String args[] )
             String outputStr; // The output string
             String str; // The entered characher
             char n; // The character entered
                   double a; // aera
             double radius; // the radius of a circle
             double area; // the area of a circle, square, rectangle, triangle
             double circumference; // the circumference of a circle
             double m; // The square side length
             double circumference1;  //  the total for a * a
             double length;  // the length of a rectangle
             double width;  // the width of a rectangle
             double circumference2;  //  the total for 2*(length + width)
             double base; // the base of a triangle
             double side1; // the first side of a triangle
             double side2; // the second of a triangle
             double hight;
             double circumference3;  //  the total for ( base + side1 + side2 )
             do
             // display the information in a JOptionPane message dialog
                str = JOptionPane.showInputDialog("Enter a character specifying a geometrical shape" +
                   "\n" + " Circle = c" + "\n" + "Rectangle = R" + "\n" + "Square = s" + "\n"
                   + "Triangle = t" );
                n = str.charAt(0); // return the caracter
                switch (n)
                   case 'c':
                   case 'C':
                   // convert String inputs to double values for use in a calculation
                      radius = Double.parseDouble(
                         JOptionPane.showInputDialog("Enter the radius of a circle:"));     
                      area = 3.14 * Math.pow ( radius, 2); // calculate the area      
                      circumference = 2 * 3.14 * radius;// calculate the circumference
                      outputStr = String.format("The area of a circle is: %.2f%n" +
                         "The circumference of a circle is: %.2f", area, circumference);
                   // display result in a JOptionPane message dialog
                      JOptionPane.showMessageDialog(null, outputStr , "The result",
                         JOptionPane.INFORMATION_MESSAGE);
                      break;
                   case 's':
                   case 'S':
                   // convert String inputs to double values for use in a calculation
                      m = Double.parseDouble(
                         JOptionPane.showInputDialog("Enter the square side length:"));     
                      area = Math.pow ( m, 2); // calculate the area         
                      circumference1 = 4 * m;// calculate the circumference
                      outputStr = String.format("The area of a square is: %.2f%n" +
                         "The perimeter of a square is: %.2f", area, circumference1);
                   // display result in a JOptionPane message dialog
                      JOptionPane.showMessageDialog(null, outputStr , "The result",
                         JOptionPane.INFORMATION_MESSAGE);
                      break;
                   case 'r':
                   case 'R':
                   // convert String inputs to double values for use in a calculation
                      length = Double.parseDouble(
                         JOptionPane.showInputDialog("Enter the length of a rectangle:"));
                      width = Double.parseDouble(
                         JOptionPane.showInputDialog("Enter the width of a rectangle:"));     
                      area = length * width ; // calculate the area     
                      circumference2 = 2* (length + width); // calculate the circumference
                      outputStr = String.format("The area of a square is: %.2f%n" +
                         "The perimeter of a square is: %.2f", area, circumference2);
                   // display result in a JOptionPane message dialog
                      JOptionPane.showMessageDialog(null, outputStr , "The result",
                         JOptionPane.INFORMATION_MESSAGE);
                      break;
                   case 't':
                   case 'T':
                   // convert String inputs to double values for use in a calculation
                      base = Double.parseDouble(
                         JOptionPane.showInputDialog("Enter the base of a triangle:"));
                      side1 = Double.parseDouble(
                         JOptionPane.showInputDialog("Enter the first side of a triangle:"));
                      side2 = Double.parseDouble(
                         JOptionPane.showInputDialog("Enter the second side of a triangle:"));
                      hight = Double.parseDouble(
                         JOptionPane.showInputDialog("Enter the hight of a triangle:"));     
                      area = 0.5 * base * hight; // calculate the area      
                      circumference3 = base + side1 + side2;// calculate the circumference
                      outputStr = String.format("The area of a triangle is: %.2f%n" +
                         "The circumference of a yriangle is: %.2f", area, circumference3);
                   // display result in a JOptionPane message dialog
                      JOptionPane.showMessageDialog(null, outputStr , "The result",
                         JOptionPane.INFORMATION_MESSAGE);
                      break;
                   default:
                   // display result in a JOptionPane message dialog
                      JOptionPane.showMessageDialog(null, " The letter you entered doesn't " +
                         "represent either a circle or a rectangle or a square" , "ERROR",
                         JOptionPane.ERROR_MESSAGE);
             while (  area > 10 );
             System.exit(0);
          } // end method main
       } // end class Sh7q6the Q is how can i say when the area < 10 stop the loop in the while logical expression..

    the Q is how can i say when the area < 10 stop the loop in the while logical expression..You're almost already doing that. You're doing this:
             while (  area > 10 );As soon as the area is 10 or below, that expression will evaluate to false and the loop will end.
    If you want to still loop when the value is 10, then change it to:
             while (  area >= 10 );

  • Help with Do/While Loops

    The user enters a number between 1&15 and the system gives 1 up unitl that number, if a person enters a number that is less than 1 and greater than 15 I want the system to say, "Must Enter number between 1 & 15" then exit. My program just ignores the fact that I put in ex. 17 and treats it like it was 15, ANy help is appreciated
    import java.io.*;
    public class Nik
    public static void main(String args[])
    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    try
    //declare variables
    String line;
    int i;
    boolean selection = true;
    boolean wrong = false;
    while (selection)
    System.out.print("Enter a number between 1 and 15:");
    line = keyboard.readLine();
    try
    i = Integer.parseInt(line);
    for (int j=1; j<15; j++) System.out.print(j+" ");
    System.out.println("");
    catch(NumberFormatException e){selection = false;}
    do
    System.out.println("You Must enter a number between 1 and 15:");
    try
    for (int j=0; j>16; j++)System.out.print(j+"");
    System.out.println("");
    catch(NumberFormatException e) {wrong=true;}
    }while(wrong);
    }catch(IOException e){}

    Your code doesn't check if the number is greater than 15 or less than 1. The loop seems a bit weird to me, this is how I would do it:
    import java.io.*;
    public class Nik
        public static void main(String args[])
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
            String line = "";
            boolean isValid = false;
            do
                System.out.println("Enter a number between 1 and 15:");
                try
                    line = keyboard.readLine();
                } catch(IOException e) {}
                int yourInt = Integer.parseInt(line);
                if(yourInt > 0 && yourInt < 16)
                    for(int j = 1; j < yourInt; j++)
                        System.out.print(j + " ");
                    System.out.println();
                    isValid = true;
                else
                    isValid = false;
            } while(isValid);
            System.out.println("Must Enter number between 1 & 15");
    }The most important part you were missing was:
    if(yourInt > 0 && yourInt < 16)but also I don't think you need 2 loops to do this.

  • 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

  • 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.

  • HELP with DO WHILE NESTED LOOPS PLEASE

    I am trying to create a very basic Airline Reservation Sytem using JBuilder 3.
    I am using JOptionPane boxes as the interface. The user has to input a number each time a menu appears and this takes him/her to the next or previous menu.
    I tried using the switch statement but as there are many combinations and more choices on some menus than others it became very complex. I am now trying nested do while loops with out much success....Can anyone help????
    A sample of my coded is included below... Thanks....
    void go () throws IOException
    int choice;
    choice = printMenu();
    do
    if (choice == 1)
    printMenu1();
    else if (choice == 2)
    printMenu2();
    while (choice !=3);
    int printMenu()
    String usersChoice, output;
    int choice;
    do
    output = "1 - Enter Airline/Flight/Passenger. \n";
    output = output + "2 - Display Airline/Flight/Passenger. \n";
    output = output + "3 - Exit. \n\n";
    output = output + "Please enter a number:";
    //get users selection
    usersChoice = JOptionPane.showInputDialog(output);
    //convert to integer
    choice = Integer.parseInt(usersChoice);
    }while(choice <1|| choice >3);
    return choice;
    }

    > void go () throws IOException
    int choice;
    choice = printMenu();
    do
    if (choice == 1)
    printMenu1();
    else if (choice == 2)
    printMenu2();
    while (choice !=3);
    int printMenu()
    String usersChoice, output;
    int choice;
    do
    output = "1 - Enter Airline/Flight/Passenger. \n";
    output = output + "2 - Display Airline/Flight/Passenger. \n";
    output = output + "3 - Exit. \n\n";
    output = output + "Please enter a number:";
    //get users selection
    usersChoice e = JOptionPane.showInputDialog(output);
    //convert to integer
    choice = Integer.parseInt(usersChoice);
    }while(choice <1|| choice >3);
    return choice;
    }Your method printMenu() returns an integer, shouldn't you catch that into choice in your go() method? You probably have already done this, but I'd make a seperate method for each menu/submenu (perhaps even create a generic menu display method, pass in an array of strings/choices, prompt for a input and return an int, much like your printMenu() does).
    kev

  • 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

  • I need help with my for loop in this array

    Ok well, I can't get my code to work. Also, please remember that this is just my draft so it isnt pretty. I will fix it up later so please look at it. The thing I want to do is look into the array for a time that matches what the user entered and return the toString() of that one. I know there is something wrong with my for loop but I cant figure how to fix it. please help. here is what i have so far:
    import javax.swing.JOptionPane;
    public class Runner
        public static void main (String[] args)
            String timeStr;
            int time, again, optiStr;
            Inbound[] in = new Inbound[25];
             in[0]=new Inbound ("",0,"On Time num0");
             in[1]=new Inbound ("",2,"On Time num1");
             in[2]=new Inbound ("",3,"Delayed num2");
             in[3]=new Inbound ("",4,"On Time");
             in[4]=new Inbound ("",5,"On Time");
             in[5]=new Inbound ("",6,"Canceled");
             in[6]=new Inbound ("",1,"Canceled num6");
             in[7]=new Inbound ("",8,"On Time");
             in[8]=new Inbound ("",9,"Delayed");
             in[9]=new Inbound ("",10,"On Time");
             in[10]=new Inbound ("",11,"Delayed");
             in[11]=new Inbound ("",12,"On Time");
             in[12]=new Inbound ("",13,"Delayed");
             in[13]=new Inbound ("",14,"On Time");
             in[14]=new Inbound ("",15,"On Time");
             in[15]=new Inbound ("",16,"On Time");
             in[16]=new Inbound ("",17,"Canceled");
             in[17]=new Inbound ("",18,"On Time");
             in[18]=new Inbound ("",19,"On Time");
             in[19]=new Inbound ("",20,"Canceled");
             in[20]=new Inbound ("",21,"On Time");
             in[21]=new Inbound ("",22,"Delayed");
             in[22]=new Inbound ("",23,"On Time");
             in[23]=new Inbound ("",24,"Cancled");
             in[24]=new Inbound ("",7,"On Time num24");
            do{
                timeStr = JOptionPane.showInputDialog ("In military time, what hour do you want?");
                time = Integer.parseInt(timeStr);
                if (time<=0 || time>24)
                 JOptionPane.showMessageDialog (null, "Error");
                 optiStr = JOptionPane.showConfirmDialog (null, "If you want Incoming flights click Yes, but if not click No");
                if (optiStr==JOptionPane.YES_OPTION)
    //(ok this is the for loop i am talking about )
                    for (int index = 0; index < in.length; index++)
                      if ( time == Inbound.getTime())
                   JOptionPane.showMessageDialog (null, Inbound.tostring());  //return the time asked for
    //               else JOptionPane.showMessageDialog (null, "else");
                }//temp return else if failed to find time asked for
    //             else
    //               if (optiStr==JOptionPane.CANCEL_OPTION)
    //                 JOptionPane.showMessageDialog(null,"Canceled");
    //              else
    //                {Outbound.run();
    //                JOptionPane.showMessageDialog (null, "outbound");}//temp
                  again=JOptionPane.showConfirmDialog(null, "Try again?");
            while (again==JOptionPane.YES_OPTION);
    }any help would be greatly appriciated.

    rumble14 wrote:
    Ok well, I can't get my code to work. Also, please remember that this is just my draft so it isnt pretty. I will fix it up later so please look at it. The thing I want to do is look into the array for a time that matches what the user entered and return the toString() of that one. I know there is something wrong with my for loop but I cant figure how to fix it. please help. here is what i have so far:
    >//(ok this is the for loop i am talking about )
    for (int index = 0; index < in.length; index++)
    if ( time == Inbound.getTime())
    JOptionPane.showMessageDialog (null, Inbound.tostring());  //return the time asked for
    Inbound.getTime() is a static method of your Inbound class, that always returns the same value, I presume? As opposed to each of the 25 members of your array in, which have individual values?
    Edited by: darb on Mar 26, 2008 11:12 AM

  • If statement on a while loop condition

    Hello,
    I was just wondering whether it was possible to have an if statement on a while loop. Basically, I have a while loop that has the following terminating condition
    do{
    //...loop code here
    while (netError > acceptableError && learningCycle < 100000 && alive);I'm looking to introduce a boolean "ignoreMaxCycles" that basically stops the loop from taking notice of the learningCycle clause of the condition.
    do{
    //...loop code here
    while (netError > acceptableError && alive);I know it can be done repeating the two loops with an if statement governing which one is executed, but I was wondering whether there was a shorter/cleaner way of doing this?
    Thanks,
    Nick

    nickd_101 wrote:
    Hello,
    I was just wondering whether it was possible to have an if statement on a while loop. Basically, I have a while loop that has the following terminating condition
    do{
    //...loop code here
    while (netError > acceptableError && learningCycle < 100000 && alive);I'm looking to introduce a boolean "ignoreMaxCycles" that basically stops the loop from taking notice of the learningCycle clause of the condition.
    do{
    //...loop code here
    while (netError > acceptableError && alive);I know it can be done repeating the two loops with an if statement governing which one is executed, but I was wondering whether there was a shorter/cleaner way of doing this?
    Thanks,
    Nick
    do {
    while(netError > acceptableError && (ignoreMaxCycles || learningCycle < 100000) && alive)wtf ? i took 2 minutes for that ?
    Edited by: darth_code_r on Aug 29, 2008 9:21 AM

  • 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]

  • Need help with an infinite loop please

    Can somebody please help me out with displaying text that's been imported from another file onto a JTextArea? this is the code i've been trying to get to work, and it does, but it is stuck in an infinite loop and i can't see why. I've tried adding a counter before the while loop, and displaying and incrementing it inside the loop. The counter gets to 32 (the last line of the file) then goes back to 1 and starts again. Any help, or explanations would be awesome, thanks.
    String line;
         while ((line=reader.readLine())!=null){
              System.out.println(num);
              append(line+" \n");
         }                              

    think you will have to post some more of the code, is that within any sort of loop itself , has it its own method ? is it an event handler ? ..btw the append sould be fine .. is this a subclass of a TextArea ? where is this bit of code ?
    Message was edited by:
    odd_function

Maybe you are looking for