Why is this loop infinite?

I only want it to iterate once and prompt the user again, until they hit enter.
public class assignment5
          public static void main(String[] args)
               System.out.println("Please type in a sentence.\nTo quit at any time hit enter.");
               String sentence = SavitchIn.readLine();
               String sentenceTrim = sentence.trim();
               int quit = sentence.length();
               int questionIndex = sentenceTrim.indexOf("?");
               int exclamationIndex = sentenceTrim.indexOf("!");
               int length = sentenceTrim.length();
               int evenOdd = length % 2;
               do
               if ((evenOdd == 0) && (questionIndex != -1))
                    System.out.println("Yes ");
               else if ((evenOdd != 0) && (questionIndex != -1))
                    System.out.println("No ");
               else if (exclamationIndex != -1)
                    System.out.println("Wow ");
               else System.out.println("You always say \"" + sentenceTrim + "\" ");
               while (length > 0);
[/colde]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Doesn't this question have a little homework
feeling??? No, not at all. His question is not "How do I make a program that returns when the user hits enter?" His question is "Why doesn't this work?"
He has already tried and is clearly not getting what he predicted. What do you expect him to do? If he didn't feel this was the time to ask a question, then he has no hope.
I think it is a very good question, although it probably belonged in the beginner forum.
To answer the original poster, just follow your code one line at a time and when it starts to do things that you don't want it to, it's time to rethink the placement of your lines and loop points (start and stop). And think about what the other posters have written.

Similar Messages

  • Why is this loop incorrect please

    Hello,
    Im trying to get a 5x5 grid of images to display on fullscreen mode.
    The only code that renders these 5 images is below. Please note, ive been testing this section out to try to fix the problem, using r + c for coords, and x and y to show the 5x5. To me, this loop goes through each y, 0 - 4 , and should display a 5 x 5 grid of images. Instead, only one row of 5, (the last one_ is shown. I really dont understand so if you can help, please do :)
            // draw the visible tiles
            int r = 1;
            int c =1;
            for (int y=0; y<5; y++) {
                for (int x=0; x <5; x++) {
                     r = r+10;
                     c=c+10;
                     Tile tile = map.getTile(x, y);
                     if (tile != null) {
                        g.drawImage(tile.base,r,c,
                            null);
            }Thankyou,
    L28

    Hello,
    thankyou for your reply. I used your code and unfortunately the output displays as 5 images, going down (eg 0,0 1,0 2,0 3,0 4,0). Swapping the x and y results in it showing 5 images left to right. Ive had a look and think the problem could be how the loop is called.
    here is how the code to render the 5x5 grid is used.
    GameLoop
      // draw the screen
                Graphics2D g = screen.getGraphics();
                draw(g);
                g.dispose();
                screen.update();
                // take a nap
                try {
                    Thread.sleep(20);...callable code
    public void draw(Graphics2D g) {
            renderer.draw(g, map,
                screen.getWidth(), screen.getHeight());
        }Using System.out.println, instead of being 25 outputs (ie the 5x5 grid), there are hundreds ( i think) of outputs (probably limited by how many lines System.out.println can display.
    Thankyou
    L28
    edit
    Hard coding the grid (replacing the loop code) produces expected output
    Tile tile1 = new Tile("GrassTile1");
            Tile tile2 = new Tile("GrassTile1");
            Tile tile3 = new Tile("GrassTile1");
            Tile tile4 = new Tile("GrassTile1");
            g.drawImage(tile1.base,0,0,
                    null);
            g.drawImage(tile2.base,0,64,
                    null);
            g.drawImage(tile3.base,0,128,
                    null);
            g.drawImage(tile4.base,0,192,
                    null);Edited by: Lance28 on Mar 29, 2008 11:54 AM

  • Why does this loop create a 3D array instead of a 2D?

    Hi,
    This should be a relatively simple question. I am feeding a 1-D array (1 x 801) in a loop into a build array function and looping it back on itself to build the array. I am rather confused as to why this is producing a 3D array, can someone explain why?
    Thank you,
    Michael
    Attachments:
    QCM.vi ‏113 KB

    Where are you seeing the 3D array? If it is at the far right of the diagram, at the edge of the FOR loop, it is because you have the autoindexing set, which is going to make a 1D array of your 2D array data, a 3D array. As the two sub-vi's didn't come with your vi I don't know what the one with the "17" as an input does, nor what the other one does either, other than apparently produce two 1D arrays.
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

  • Why does this loop used to write values to the parallel port keep going forever?

    Have a look at this VI guys. I'm trying to send a sequence of bits (used to trigger an IC). I'm interested in the last bit of the data port (D0). so I'm sending either 0 or 1 to that pin to trigger the IC. it works, but the problem is that the loop keeps going forever and i cant control it. if i send 3 to the loop count, I'm expecting to get: 1 0 1 0 1 0, but it doesnt stop and keeps going forever.
    It seems that the problem is not with the loop. because i deleted the loop and just left the flat sequence so that it executes only once, but still it keeps repeating. How can i make the flat sequence execute only once?
    I'm using a parallel port monitor (parmon.exe) and a LED connected to D0 of the parallel port to check.
    If anybody has an alternative or better method to send the bits to the parallel port, I'd be very thankful.Message Edited by krayzie on 05-14-2005 04:33 PM
    Attachments:
    pport.vi ‏24 KB

    It works just fine here. Place an indicator to the iteration terminal [i] to watch how things progress. Do the number ever increase above N-1 to what you wire to N? I don't think so!
    Also make sure you don't run the VI with the "Continuous run" button. In this case the VI would immediately restart whenever it is finished. use the "Run" button.
    LabVIEW Champion . Do more with less code and in less time .

  • Why is this looping?

    This is the second time I have come across this issue. Not
    exactly sure they are the same, but they seem to be. As you can
    see, I have added traces just about everywhere so I can see exactly
    what is going on.
    Here is the resulting output from the traces as a result of a
    SINGLE click!
    Paused: false
    1
    Channel Pos: 928.7981859410431
    2 - Should keep going
    2.5 - end if - Should Stop Here
    Paused: true
    Paused: true
    3
    4
    5 - end else - Should Stop Here
    Paused: false
    1
    Channel Pos: 0
    2 - Should keep going
    2.5 - end if - Should Stop Here
    As you can see, for some reason, it blows right past the end
    of the
    if, right through the
    else, and back into the
    if before finally stopping. I have no idea why it keeps
    going, and I have no idea why it stops when it does!

    >>it looks like the function is being entered more than
    once<<
    Yes, but why? What on earth could be causing it?

  • Why isnt this loop working?

    I am trying to fill an array with the Fibonacci sequence.
    Oh and, I know its very silly to use 'long i' instead of 'int i' as my incrementor in the for loop. But... I have a reason.
    import java.math.*;
    public class euler20{
         public static void main (String arghp[]){
              BigInteger a[]=new BigInteger [1000000];
              a[1]=new BigInteger("1");
              a[2]=new BigInteger("2");
              for(long i=3;i<10;i++)     
                        System.out.println(a[(int)i]);
                        a[(int)i]=new BigInteger(""+a[(int)i-1].add(a[(int)i-2]));
              Tell me I am doing something REALLY stupid..

    uhm well, I imporvised my code a little..
    replace a[(int)i]=new BigInteger(""+a[(int)i-1].add(a[(int)i-2]));with
    a[(int)i]=a[(int)i-1].add(a[(int)i-2]);However, the problem persists.

  • Better Way to do this loop.

    I know there is better ways to do this so that I can merely have it loop infinitely until it hits the max password. I would also like to keep the spot where it has the print Statements because I tend to set some other code in front of it.
    If anyone also has some Ideas so I can have it stop and start in particular positions.
    Like lets say ?!!!!? to ?~~~~?
    Thanks a ton. Below is the code.
       char[] password = new char[20];
       int current_last_letter = 0;
       int max_password = 3;
       while(current_last_letter < max_password)
       for(int counter_gamma = 32; counter_gamma <= 126; counter_gamma++)
           for(int counter_beta = 32; counter_beta <= 126; counter_beta++)
                for(int counter_alpha = 32; counter_alpha <= 126; counter_alpha++) //alpha = increase last character by one
                    password[current_last_letter] = (char)counter_alpha;
                    System.out.print(password);
                    System.out.println("::null");
                if(current_last_letter > 0)
                    password[current_last_letter-1] = (char)counter_beta;
                else
                    counter_beta = 127;
            if(current_last_letter > 1)
                password[current_last_letter-2] = (char)counter_gamma;
            else
                counter_gamma = 127;
       current_last_letter++;
                   

    If I interpreted your code right, you simply want to count in radix '~'-' '+1 (read this carefully).
    Given a password, and a lo/hi value for the character range, the following method returns the
    lexicographically next password. The method returns null if no such password exists --    char[] nextPassword(char[] pw, char lo, char hi) {
          for (int i= pw.lenght; --i >= 0;)
             if (pw[i] < hi) { // next character possible here?
                pw[i]++;
                return pw;
             else // * no, reset to first value and continue;
                pw= lo;
    return null; // all pw-chars reached their hi value
    So, if you initialize a password char array as follows --    char[] pw= new char[20];
       Arrays.fill(pw, ' '); the following fragment handles every possible password --    do {
          handlePassword(pw); // do something with pw
          pw= nextPassword(pw, ' ', '~');
       } while (pw != null); kind regards,
    Jos

  • [solved] C: What am I missing in this loop/switch?

    I'm quite new to C. I'm trying to put together a simple menu (in console), where the program presents a few choices, the user enters a choice, and is then prompted for further information. What I have is this:
    int main ()
    char selection;
    char data;
    while (selection != 'q') {
    printf ("MAIN MENU\n\n");
    printf ("a\nb\nc\n");
    printf ("Enter choice: ");
    scanf ("%c", &selection);
    switch (selection) {
    case 'a':
    printf ("Enter a: " );
    scanf ("%c", &data);
    break;
    case 'b':
    printf ("Enter b: " );
    scanf ("%c", &data);
    break;
    case 'c':
    printf ("Enter c: " );
    scanf ("%c", &data);
    break;
    default:
    printf ("Default.\n");
    break;
    printf ("You entered %c.\n\n", data);
    printf ("\nGoodbye.\n\n");
    What I want is this:
    $ ./a.out
    MAIN MENU
    a
    b
    c
    Enter choice: a
    Enter a: A
    You entered A.
    MAIN MENU
    a
    b
    c
    Enter choice: q
    Goodbye.
    What I get is this:
    $ ./a.out
    MAIN MENU
    a
    b
    c
    Enter choice: a
    Enter a: You entered
    MAIN MENU
    a
    b
    c
    Enter choice: q
    Goodbye.
    I don't understand why it's looping through again after executing the case's printf () but before the case's scanf () statement. I assume there's some nuance of either switch(), printf(), or scanf() to which I'm not yet privy. Or maybe some really, really dumb newbie mistake. Can anyone enlighten me?
    (PS: It's not homework, even though it probably looks like it. I threw together this simple example rather than edit the code of the actual project.)
    Thanks!
    Last edited by ibrunton (2011-07-08 02:09:24)

    tavianator wrote:
    Guff wrote:scanf("%1s", &selection) might do the job.
    Do NOT do this, because it'll write '\0' to *(&selection + 1), which is a random location somewhere on your stack.
    Glad I didn't try that one, then. After some googling and man pages, I ended up using this (putting it here in case it happens to help anyone else in the future):
    int input;
    char selection;
    while ((input = getchar ()) != "\n")
    selection = (char)input;
    Worked like a charm every time.

  • Why is this file locked (man chflags), does it need to be, and is it safe to unlock it?

    Why is this file locked (man chflags), does it need to be, and is it safe to unlock it?
    ~/Library/Application Support/Adobe/Enterprise/Resources/Resource_3_1.db
    Type this into a terminal in OS X, the above file appears to have a flag set to lock.
    x-man-page://chflags

    <the-sound-of-crickets>
    The reason I'm asking, we have a bunch of computers we inherited that have some permissions issues within each user's respective home directory ("~"). The issue effects Acrobat Pro X's ability to launch ("Internal error occurred") since it tries to get access files/folders it doesn't have access to when the user launches. Recursively setting ownership to the respective user fixes the problem (and follows Apple's guidelines). However, that one file appears to have the unix file lock set (man chflags). So we are using a pre-installation script on our push policy to loop through every home directory. It appears the above file is the only one that won't let us change permissions.
    Don

  • Why's this sound at the beginning of my recording?

    After I send a song to iTunes, there's always a faint drum/synth sound heard later in the song that shows up at the very beginning of the track when it's not supposed to be there. Why is this? Is it because I haven't selected the loop and set the duration?

    rsherid wrote:
    After I send a song to iTunes, there's always a faint drum/synth sound heard later in the song that shows up at the very beginning of the track when it's not supposed to be there. Why is this? Is it because I haven't selected the loop and set the duration?
    This may be a manifestation of a lingering bug in the audio engine that caches a reverb tail from the last play. If it's what I'm thinking of, a workaround would be to select all the tracks of your song, and move them all forward, in sync, about a measure or two. Looking at your tracks, it will appear as if the beginning of the song is now at measure 2 or 3 instead of 1. That way, there will be a moment of silence at the very beginning of the song (that clears out the cache), but then everything will start normally and play to the end, and it will get rid of the ghost echo at the beginning.

  • Why does this ring operation occasionally give an error?

    I am using LabWindows/CVI, and I created a low-level ring acquisition. It works normally at first, but if I stop it and start a few times (does not always happen on the first stop / start cycle), then I get the error:
    NON-FATAL RUN-TIME ERROR: "Dalsa.c", line 2716, col 13, thread id 0x000012A4: Function imgSessionCopyBuffer: (return value == -1074397014 [0xbff600aa]).
    The requested buffer has been overwritten and is no longer available. It occurs on the second line of the following code:
    (2715) imgGetAttribute(Sid, IMG_ATTR_LAST_VALID_BUFFER, &currentRingBufNum);
    (2716) imgSessionCopyBuffer(Sid, currentRingBufNum, (uInt8*)pixel_address, FALSE);
    I stop my acquisition by :
    imgSessionAbort(Sid, &ringBufNum);
    Then I unlock my ring buffer, dispose each element, and finally dispose of the buffer list. The next acquisition starts by creating a buffer list, creating and allocating each element, locking the buffer list, and configuring the session to use that buffer list. I am NOT closing the session or the interface, I only do that upon quitting my program. Why do I get this error??
    Buffer creation code:
    //Create a buffer list
    imgCreateBufList(NUMRINGBUFFERS, &Bid);
    //Find out how big the buffers should be in memory
    imgGetAttribute(Sid, IMG_ATTR_BYTESPERPIXEL, &bytesPerPixel);
    bufSize = AcqWinWidth * AcqWinHeight * bytesPerPixel;
    //Create the ring buffer
    for (i = 0; i < NUMRINGBUFFERS; i++)
    //Create individual buffer elements
    imgCreateBuffer(Sid, IMG_HOST_FRAME, bufSize, &ringBuffer[i]);
    //Now tell the buffer list where these buffers are by populating them into the Buffer List Bid
    imgSetBufferElement(Bid, i, IMG_BUFF_ADDRESS, (uInt32)ringBuffer[i]);
    imgSetBufferElement(Bid, i, IMG_BUFF_SIZE, bufSize);
    //If we are still filling the buffer, this configures the current buffer on the list to move to the next buffer
    //If we are configuring the last buffer in the list, this buffer will now loop to the first element when it is filled
    bufCmd = (i == (NUMRINGBUFFERS - 1)) ? IMG_CMD_LOOP : IMG_CMD_NEXT;
    imgSetBufferElement(Bid, i, IMG_BUFF_COMMAND, bufCmd);
    //Locks the buffers in the buffer list
    imgMemLock(Bid);
    //Configure the session to be a ring acquisition using our buffer list
    imgSessionConfigure(Sid, Bid);
    Buffer disposal code:
    //Unlock the ring buffer memory
    if (Bid) imgMemUnlock(Bid);
    //Free the ring buffer memory
    for (i = 0; i < NUMRINGBUFFERS; i++)
    if (ringBuffer[i] != NULL)
    imgDisposeBuffer(ringBuffer[i]);
    ringBuffer[i] = NULL;
    //Free the buffer list
    if (Bid) imgDisposeBufList(Bid, FALSE);
    Bid = 0;

    I have made some progress on narrowing the error down, but it still remains a large problem. Error trapping allows me to avoid the necessity of rebooting the system. However, I must still close and re-open my LabWindows application in order to successfully acquire from a ring.
    I have narrowed the problem down to the buffer index provided by "imgSessionStatus" : on the acquisition that throws an error, it returns "-1" as the current buffer index. Why is this??
    I have modified my program so that I close both the session and the interface when I hit "Stop", and yet I'm still receiving this problem when I attempt to restart the ring acquisition after stopping.  I have also started using "imgStopAcquisition" instead of "imgSessionAbort".  What could I not be properly resetting after I free, dispose and close the buffers, buffer list, session and interface?  Obviously the resource is being properly freed upon application closure, so I must be missing something ...

  • Some of the entries in my address book show birthdays one day/year earlier in Ical. I cannot change this except by putting in the birthdays a day/year earlier than they are. Why is this happening only for some entiries and not others?

    Some of the birthdays I have entered in Address book appear in my Ical one day and one year earlier than the date I have given. Eg. I have entered a birthday in Address book as 23 March 2011 and it appears in Ical as being on 22 March 2010. Other names have no problems. There are only some that do not appear with the correct date and year. Why is this?  Has anyone found how to correct this strange problem?  I have Time Zones ticked.
    Bronze2011

    I'm having this exact same problem, but it's doing it with a bunch of birthdays. I also did 0001 when I didn't know the birth year, so I went back and did a more current year, but they still aren't showing up where they should be...or at all. It's completely bizarre.

  • I have installed snow leopard 10.6.8 on my macbook, i got a problem that every time i want to save or put something on desktop it, says you dont have permisson why is this, also my dock want stay the same everytime i start up it defaults back?

    i have installed snow leopard 10.6.3 on to my macbook which was currently 10.4.11, i wanted to do this so i can run Final Cut Pro 10 which needs 10.6.8 or higher. so i updated the snow leopard to 10.6.8 installed final cut pro ok. the problem i got is else where i cant save on put anything on desktop, it says i dont have permisson, and when i try and click on my documents same again. also i adjusted my dock to smaller added a few applications onto it, but every time i restart the laptop it defaults back why is this?!! so annoying. i had a look at my disk utilites and i have still got 10.4.11 on my Macintosh i can switch too? i installed the snow leopard 10.6.3 on my Data Disk. can anyone help me out why i am getting these problems and what i need to do to solve it?

    disk0s2: I/O error.
    disk0s2: I/O error.
    The MBP's disk is damaged and requires replacement.
    Genius Bar Reservations: http://www.apple.com/retail/geniusbar/

  • HT1349 I can not run the scanner in my main user, but only the second user and the same thing with updating apps! Why is this happening???

    I can not run the scanner in my main user, but only the second user and the same thing with updating apps! Why is this happening???

    Welcome to the Apple Community.
    Enter the details of her second account at system preferences> mail, contacts & calendars.

  • I cannot send an email from my iPad 2? No problem receiving, why does this happen? Have tried the suggestions for setting up email and after doing the sync mail through iTunes receiving worked great but still cannot send? Any help would be great

    I cannot send an email from my iPad 2? No problem receiving, why does this happen? Have tried the suggestions for setting up email and after doing the sync mail through iTunes receiving worked great but still cannot send? Any help would be great!

    The fact that you can receive means you have a valid e mail address, and have established the connection to the incoming server, so all of that works.  Since the send does not work, that means your outgoing server is rejecting whatever settings you used formthe outgoing set up.  Try them again. 
    Google your particular isp, and ipad and many times you will find the exact settings needed for your isp.  Or tell us here, and soneone else may be on the same isp.  Some mail services need you to change a port, or have a unique name for the outgoing server.  
    Kep trying.

Maybe you are looking for