Noob Help with While Loop

Sorry for the "Noob"-ness on this one. I am working on a program for class and I am having a problem with a while loop. So I opened a new document and began to code a while loop that is basic to test my while looping skill. Apparrently, I have none. Can anyone tell me why this While Loop will not work:
public class test
     public static void main(String[] args)
     int LoanTerm = 0;
          while (LoanTerm < 3);
               System.out.println (LoanTerm);
               LoanTerm++;
Thanks.
FatherVic

to explain, the ; means that the while loop body is empty, and you will just spin forever testing whether LoanTerm < 3, without doing anything else.

Similar Messages

  • Need help with while loops

    Hello let me first explain what im trying to achive:
    I want a moving square that you control with the arrow keys on the keyboard. It has to be smooth ie able to move fast without looking like its jumping and it has to be able to move diagonaly aswell. Think of that arcade game Raiden ...you know the birds-eye view plane flying game...another thing! I'd prefer if it didnt use timers - i made one already using 4 timers and it works great but 4 timers is a little extreme - SO NO TIMERS !
    I was thinking while loops, but i cant seem to get it working. I dont want to put in all the code so ill just say that I have 4 booleans: up, down, left right and the following code:
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_UP) {
    up = true;
    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    down = true;
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    left = true;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    right = true;
    repaint();
    For the KeyReleased part i have the same as above exept it sets the booleans to false.
    Soooo in theory if i set up a while loop like this (using the up direction as an example) :
    while (up == true) {
    [move square up]
    So therefore when i press and hold the up arrow the loop will keep going untill i realease it right? WRONG ! it just keeps repeating indefinatly and it doesnt even do the " [move square up] " bit. I put a System.out.print in the loop to test and it kept printing out the message but it still didnt do the actual " [move square up] " bit.
    Im not sure if im putting the while loop in the right place either....If anyone has any idea on how to use while loops in this way please heeeelp ! Its so annoying because it just doesnt work ive tried so many ways...
    any help would be greatly apreciated !!!!

    Maybe you want something like this? You have to pause during the loop to allow for other events to happen, like if y ou release a key or whatever.
    while( true )
       if( up ) moveUp();
       else if( down ) moveDown();
       if( left ) moveLeft();
       else if( right ) moveRight();
       try
          Thread.currentThread().sleep(10);
       catch( InterruptedException e )
          System.out.println( "Thread interrupted!");
    }

  • Need help with while loop and shift registers

    I have a large data set and need to read in the data at maybe 200 samples at a time, process these samples through my VI, and have it append and concatenate a separate lvm file.  The part where I am confused is the shift registers. How do I limit the number of samples read in an iteration? How do I get the while loop to stop when all the data are read in?
    I've attached my diagram, maybe there is something wrong with my technique?
    Solved!
    Go to Solution.
    Attachments:
    shiftreg.JPG ‏56 KB

    This will give you an idea.  There are plenty of other (probably more efficient) methods.  This is a basic, quick and dirty solution to help you grasp the overall concept.
    Using LabVIEW: 7.1.1, 8.5.1 & 2013
    Attachments:
    ShiftRegLoop.JPG ‏54 KB

  • Help with while loops

    Im trying to create a while loop that outputs the revers of a string, eg nice one
    would be "eno ecin" Assuming i already have declared a variable intital string that holds the string, how do i go about this does anyone have any problem solving techniques. The charAt method needs to be used.

    i have a exam on saturday and it was a previous exam question that im trying to get help with i need to understand the course material thanks, i know how to use while loops but have trouble getting my head around this question. ill show you my code however i know its completely wrong.
    now i know i hvae to use the charAt method to return a character located at the integer i
    so i must go down after each case has been tested true therefore i want i=i-1;
    until i=0;
    String initialString="tucan";
    int i=initialString.length();
    while(i>0)
         return charAt();
         i=i-1;
         }

  • Help with while loop program

    I am working on this program that when inputing two integers: firstNum and secondNum, the program will output all odd numbers between firstNum and secondNum.
    This program will be using a while loop and I can't find any similar examples in my book on how to write the code.
    any help would be greatly appreciated

    you asked for it...
    //This program will prompt the user to input two integers.
    //Output all odd numbers between firstnum and secondnum.
    //Output the sum of all even numbers between firstnum and secondnum.
    //Ouput the numbers and their square between 1 and 10.
    //Output the sum of the square of odd numbers between firstnum and secondnum.
    //Output all uppercase letters.
    import java.io.*;
    public class Program8
              static BufferedReader keyboard = new
                        BufferedReader(new InputStreamReader(System.in));
              public static void main(String[] args) throws IOException
              //Declare all variables
              int firstNum;
              int secondNum;
              System.out.print("Input first Integer: ");
              firstNum = Integer.parseInt(keyboard.readLine());
              System.out.println();
              System.out.print("Input second Integer: ");
              secondNum = Integer.parseInt(keyboard.readLine());
              System.out.println();
    As you can see, I don't have a clue where to begin after this...

  • Need help with while loop

    Hi,
    I'm running a while loop to run through some results of a search. Anyway I know how to list the strings but my last item is a JComboBox (drop down box.) How do I go about changing that so its right for a drop down box. Its the one with questions marks in the code below.
            while (srs.next())
            //Get the values for each field in this row
            String projectName = srs.getString("PROJECT_NAME");
            System.out.println("Project Name = " + projectName );
            String projectOfficier = srs.getString("PROJECT_OFFICER");
            System.out.println("Project Officer = " + projectOfficier );
            String projectDescription = srs.getString("PROJECT_OFFICER");
            System.out.println("Project Description = " + projectDescription );
            String paymentSchedule = srs.getString("PAYMENT_SCHEDULE");
            System.out.println("Payment Schedule = " + paymentSchedule );
            String banksInvestment = srs.getString("BANKS_INVESTMENT");
            System.out.println("Banks Investment = " + banksInvestment );
        ?   String paymentsMade = srs.getString("PAYMENTS_MADE");
        ?   System.out.println("Payments Made = " + paymentsMade );Thanks.

    Yeah the Payments Made part is a JComboBox with 3 so called strings inside it. I wanna know instead of srs.getString what should I put in to replace String to get the results from a JComboBox?

  • Need help with while loop format

    I'm building a form - everything works but I would like to change the way the data is output into the table.
    In other scripting languages, like PHP, you had 2 different ways of dealing with a loop:
    <?
    do while xyz
    do something here
    ?>
    - OR -
    <? do while xyz:?>
    do something here
    <?end while ?>
    I would like to do something similar to the 2nd example in .jsp but I'm not sure of the format or how to stop the loop. From the tutorial, I'm using
    <%
    while(SQLResult.next())
    UId = SQLResult.getString("uid");
    FName = SQLResult.getString("fname");
    LName = SQLResult.getString("lname");
    out.println("<tr><td>" + UId + "</td><td>" + FName + "</td><td>" + LName
    + "</td></tr>");
    %>
    Could anyone point me in the right direction? I'd prefer it if I didn't have to build the table like this if I don't have to but haven't found anything anywhere telling me otherwise.
    Thanks so much.
    Bob

    Sorry - the answer was in JSP:Java Server Pages by Barry Burd. I had just gotten the output format wrong.

  • Help with while loop

    Im trying to finish this loop for a guessing game, does anyone have any suggestions, thanks.
    class guess
    {public static void main ( String[] args )
    int secretNumber = 4;
    InputStreamReader inStream =
    new InputStreamReader( System.in ) ;
    BufferedReader stdin =
    new BufferedReader( inStream );
    String userGuess;
    int guess;
    System.out.println("Enter your guess:");
    userGuess = stdin.readLine();
    guess      = Integer.parseInt( userGuess );
    System.out.println("You entered:" + guess );
    if ( guess = secretNumber )
    System.out.println ("Guess is correct!")
    else
    System.out.println ("Guess is incorrect")
    while ( (guess == secretNumber) = false ) //evaluates true or false
    }

    Hie.
    Your logic is not good here.
    You should do this :
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Random;
    public class Guess {
         public static void main(String[] args) {
              BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
              int secret = new Random().nextInt(10);
              boolean guessed = false;
              System.out.println("Guess the number (0 to 9, inclusive) :");
              while (!guessed) {
                   System.out.print("Your guess : ");
                   System.out.flush();
                   int guess = -1;
                   while (-1 == guess) {
                        try {
                             guess = Integer.parseInt(in.readLine().trim());
                             if (0 > guess || guess > 9) {
                                  System.out.println("You should type an integer between 0 and 9 inclusive.");
                                  guess = -1;
                        } catch (NumberFormatException nfe) {
                             System.out.println("Type an INTEGER !");
                             guess = -1;
                        } catch (Throwable t) {
                             t.printStackTrace();
                             guess = -1;
                        guessed = guess == secret;
                        if (!guessed && -1 != guess) {
                             System.out.println("Wrong ! Try again.");
              System.out.println("Right ! bye.");
    }Tell me if you need explanations.

  • Help with do loop

    do{     
    if((orderType != 'g') || (orderType != 'w')){     
    System.out.println("Please enter g or w only.");
    }while((orderType == 'g') || (orderType == 'w'));
    I need help with this loop... I have to make sure it will be able to pop the input back after the invalid input... i tried to fix it...wont stop and stay in same loop till it gets the valid before go to other loop... how? am i missing something?

    I know you've already been answered, but just a bit more...
    if((orderType != 'g') || (orderType != 'w'))That would always be true. All characters are either not equal to 'g' or not equal to 'w'.
    'x' : neither 'g' nor 'w'. Evaluates to true.
    'g' : not 'w', still evaluates to true.
    'w': not 'g', still evaluates to true.

  • Time not stopping with while loop

    Hello,
    I've attached my VI.  I am having trouble with while loops.
    I want to turn on LEDs. The first LED should turn on after 3s.  The second LED should turn on after 5s.  The third LED will turn on later. 
    The LEDs turn on based on the following conditions:
    Case 0: numeric control > 10 then led_1 off, led_2 off, led_3 off
    Case 1: numeric control <= 10 then led_1 on, led_2 on, led_3 on
    Case 2: numeric control <=5 then led_3 on
    Because of the way I'm delaying time, I have the following problems
    Case 1 --> case 2: led_3 doesn't come on right away
    Case 2 --> case 1: led_3 doesn't turn off right away
    Putting probes in certain areas leads me to believe that these problems are due to the way the time delay is being generated.
    Thanks in advance.
    EDIT: Looking at it more...it seems to be that when the stop condition is true, the loop runs one more iteration. Is there a way to keep it from running that "one more iteration."
    Attachments:
    timing.vi ‏15 KB

    One of the problems is that your VI is not able to "breathe" because it is sometimes trapped inside inner loops that consume all CPU and step on each others toes. All you need is an single outer loop and a few shift registers.
    May of your specifications are still not clear, for example what should happen to LED 1&2 in case #3? Should they remain in the state they are in, or should they turn off, for example.
    Here is a simple rewrite that spins the outer loop at a regular rate, has no inner loop, and does not need any local variables or value property nodes. See if it makes sense. Also note that your code can be simplified dramatically by using arrays. Since the stop button is read with each of the regular interations, we don't need to worry about sequencing.
    Most likely you need to do a few simple modofications, because your specs are not clear.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    timingMODCA.vi ‏15 KB

  • Timing with while loop

    Hello,
    How can I do a time with while loop?. I want to read a data in the While- Loop for 1 sec and then go to B .. I added a pic,
    Attachments:
    while- loop.GIF ‏6 KB

    nichts wrote:
    Hello,
    How can I do a time with while loop?. I want to read a data in the While- Loop for 1 sec and then go to B .. I added a pic,
    I would use as GerdW has mentioned,"elapsed time.vi" in a statement 1st case structure, after set time has elapsed> goto 2nd case structure. try not to use flat sequences....this can be done with case statements with transitional coding. I have noticed young LV programmers like to use flat sequences...I think it's a trap set up by LV developers? 

  • Ending Java War game with while loop

    How would i go about ending a java war game witha while loop. I want the program to run until all of the values of one of the arrays of one of the players split decks has all null values.

    GameObject[] theArrayInQuestion;
    // populate array somehow or other
    void methodWithLoop() {
       while(arrayNotNull(theArrayInQuestion)) {
       // do stuff
    boolean arrayNotNull(Object[] array) {
      int len = array.length;
      for(int i = 0; i < len; i++) {
        if ( array[i] != null ) {
          return true;
      return false
    }

  • Probably simple problem with while loops

    I was programming something for a CS class and came across a problem I can't explain with while loops. The condition for the loop is true, but the loop doesn't continue; it terminates after executing once. The actual program was bigger than this, but I isolated my problem to a short loop:
    import java.util.Scanner;
    public class ok {
    public static void main(String[] args){
         Scanner scan = new Scanner(System.in);
         String antlol = "p";
         while(antlol == "p" || antlol == "P"){
              System.out.println("write a P so we can get this over with");
              antlol = scan.nextLine(); 
    //it terminates after this, even if I type "P", which should make the while condition true.
    }

    Thanks, that worked.
    I think my real problem with this program was my CS
    teacher, who never covered how to compare strings,Here's something important.
    This isn't just about comparing Strings. This applies to comparing ANY objects. When you use == that compares to see if two references refer to the same instance. equals compares objects for equality in the sense that equality means they have equal "content" as it were.

  • Problem with while loops, please help!

    I am having quite a bit of trouble with a program im working on. What i am doing is reading files from a directory in a for loop, in this loop the files are being broken into words and entered into a while loop where they are counted, the problem is i need to count the words in each file seperately and store each count in an array list or something similar. I also want to store the words in each file onto a seperate list
    for(...)
    read in files...
         //Go through each line of the first file
              while(matchLine1.find()) {
                   CharSequence line1 = matchLine1.group();
                   //Get the words in the line
                   String words1[] = wordBreak.split(line1);
                   for (int i1 = 0, n = words1.length; i1 < n; i1++) {
                        if(words1[i1].length() > 0) {
                             int count= 0;
                                           count++;
                             list1.add(words1[i1]);
              }This is what i have been doing, but with this method count stores the number of words in all files combined, not each individual file, and similarly list1 stores the words in all the files not in each individual file. Does anybody know how i could change this or what datastructures i could use that would allow me to store each file seperately. I would appreciate any help on this topic, Thanks!

    Don't try to construct complicated nested loops, it makes things a
    tangled mess. You want a collection of words per file. You have at least
    zero files. Given a file (or its name), you want to add a word to a collection
    associated with that file, right?
    A Map is perfect for this, i.e. the file's name can be the key and the
    associated value can be the collection of words. A separate simple class
    can be a 'MapManager' (ahem) that controls the access to this master
    map. This MapManager doesn't know anything about what type of
    collection is supposed to store all those words. Maybe you want to
    store just the unique words, maybe you want to store them all, including
    the duplicates etc. etc. The MapManager depends on a CollectionBuilder,
    i.e. a simple thing that is able to deliver a new collection to be associated
    with a file name. Here's the CollectionBuilder:public interface CollectionBuilder {
       Collection getCollection();
    }Because I'm feeling lazy today, I won't design an interface for a MapManager,
    so I simply make it a class; here it is:public class MapManager {
       private Map map= new HashMap(); // file/words association
       CollectionBuilder cb; // delivers Collections per file
       // constructor
       public MapManager(CollectionBuilder cb) { this.cb= cb; }
       // add a word 'word' given a filename 'name'
       public boolean addWord(String name, String word) {
          Collection c= map.get(name);
          if (c == null) { // nothing found for this file
             c= cb.getCollection(); // get a new collection
             map.put(name, c); // and associate it with the filename
          return c.add(word); // return whatever the collection returns
       // get the collection associated with a filename
       public Collection getCollection(String name) { return map.get(name); }
    }... now simply keep adding words from a file to this MapManager and
    retrieve the collections afterwards.
    kind regards,
    Jos

  • Help needed with while loops please :)

    I'm beginning to study java at School.
    My assignment using while loops, to ask user to input 2 numbers.
    I have to output all odd number between the two.
    I have to output the sum of all even numbers between the two.
    Output all the numbers and their squares between 1-10.
    Output the squares of the odd numbers between the 2 numbers the user entered.
    Output all uppercase letters.
    If anyone can give me any help, I would appreciate it greatly.
    Thank you.
    Kelly.

    It would help if you put aside your code, and wrote out some pseudo-code first so that you understand the steps you will need to take. for example
    get input from user
    set counter to first number entered
    while counter less than/ equal to second number
          check if number is even
               if even, add to even_sum
               else output counter, along with its square
          increment counter by one
    end while
    output sum of evensthat block, when coded, will solve 3 of the problems, the other 2 will require separate loops
    Good Luck

Maybe you are looking for

  • My purchases do not show up on my computor

    i am using my apple ID for myself and my wife.  On her computor it shows that i have purchased certain audiobooks, but those do not show up on her computor.  i have chaecked and have enabled automatic downloads.  i have also tried repurchaseing,, but

  • Vendor Invoice Payment (Urgent please)

    Hi Need to know I have done Down payment to Vendor F-47 of Rs 3000 then did F110 and paid the vendor throguh Check. Now I created a PO of Rs 8500 and did GR and so while doing Invoice of it showed me 3000- down payment exists. Show how can  I did the

  • Any HD for the Mac 512 ?

    Hi, I have a Mac 512 with a damaged FloppyDisk (the disks don't come out). I couldn't find a HD 20. My question: Is it possible to connect (and boot with it) any other (HD-) bus? perhaps wit husing an adapter (serial – SCSI) ? The later models of the

  • HT201269 How do I take a phone off my iTunes after selling it so the other person can use it?

    I've upgraded and had my iPhone 4S unlocked but the new owner says it's linked to my Apple ID How can I unlink it so they can use it?

  • Batch Input doubt

    Wassup guys ... Here is the problem. I did a program thar reads data from a legacy system and update Vendor doing a batch input on XK02. XK02 has a customer exit implemented, but, when I'm doing the doing input the exit should not be execute. I tryie