Page 1 of 2 12 LastLast
Results 1 to 20 of 40
  1. #1
    hungdukie is offline Member
    Join Date
    Nov 2008
    Posts
    32
    Rep Power
    0

    Question While and do while statements questions

    I am doing a lab the asks me to replace some for statements with a while and do while statements. I am totally lost. I'll paste the original code with the for statements:
    Java Code:
      for (int x = 1; x <= height; x++)  //replace this loop with a while loop
      {
         if (x == 1 || x == height)
         {
        for (int y = 1; y <= width; y++)  //replace this loop with a do-while loop
          {
        System.out.print(symbol);
          } //end for loop
         } //end if
      
        else{ 
           System.out.print(symbol);
           for (int w = 2; w <= width-1; w++){
              System.out.print(" ");}
       
           System.out.println(symbol);
        } //end else
         System.out.println();
      }//end for
    The following is the code I have tried:
    Java Code:
       x = 1;
    	while ( x <= height)
    	{
    
    	System.out.print(symbol);
    	 x++;
    	 }  //replace this loop with a while loop
    
      {
         if (x == 1 || x == height)
         {
        do    //replace this loop with a do-while loop
          {
        System.out.print(symbol);
    	 y++;
          } //end for loop
    
    		while (y = 1);
         } //end if
      
        else{ 
           System.out.print(symbol);
           for (int w = 2; w <= width-1; w++){
              System.out.print(" ");}
       
           System.out.println(symbol);
        } //end else
         System.out.println();
      }//end for
    I obviously have it all wrong. Can anyone help me or at least point me in the right direction? Thanks.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Your two loops must nest. That is the do-while loop needs to be found within the while loop, just as the for loops currently being used are nested.

    Suggestion: be very careful to use correct indentation when writing code. not only will it help others to be better able to read your code, it will also help you to catch errors such as the above.

    Good luck!

  3. #3
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default Almost....

    Graphically, what Fubarable is saying is:
    Java Code:
    [COLOR="Blue"]while (x <= height;)
         [B]{[/B][/COLOR]
             //calc stuff with x...
            [COLOR="DarkOrange"]do
               [B]{[/B][/COLOR]
                  //calc stuff with y
               [COLOR="darkorange"][B]}[/B] while (y <= width)[/COLOR] //end do-while
         [COLOR="blue"][B]}[/B][/COLOR]//end while
    Recommentdations:

    Have to declare what type the variable "x" is.
    x = 1;

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  4. #4
    hungdukie is offline Member
    Join Date
    Nov 2008
    Posts
    32
    Rep Power
    0

    Default

    Okay, I am trying to nest the do-while loop within the while loop but I still must not be doing it right because I keep getting a compiler error saying while expected and pointing to the 2 last braces. Here is the code I am trying:


    height = Integer.parseInt(JOptionPane.showInputDialog("Plea se enter the height.\n"));
    width = Integer.parseInt(JOptionPane.showInputDialog("Plea se enter the width.\n"));

    System.out.println("Rectangle = " + height +" rows by "+ width + " columns");
    x = 1;
    while ( x <= height)
    {
    System.out.print(symbol);
    x++;
    } //replace this loop with a while loop

    do {
    if (x == 1 || x == height)

    //replace this loop with a do-while loop

    { System.out.print(symbol);
    y++;}
    //end for loop




    else
    {System.out.print(symbol);
    for (int w = 2; w <= width-1; w++){
    System.out.print(" ");}

    System.out.println(symbol);}
    //end else
    {
    System.out.println();}
    while (y = 1);
    }
    }
    }

  5. #5
    hungdukie is offline Member
    Join Date
    Nov 2008
    Posts
    32
    Rep Power
    0

    Default

    I think I am getting closer.. do I need to declare x and y as int variables? If I do where would I declare them at the beginning? I am now getting errors saying cannot find symbol for x and y.
    I placed a brace at the end of the code before the last part of the while statement like so:
    Java Code:
       System.out.println("Rectangle  = " + height +" rows by "+ width + " columns");
    x = 1;
    while ( x <= height)
    {
      {   System.out.print(symbol);
         x++;
      } //replace this loop with a while loop
    
    do {
    if (x == 1 || x == height)
    
    //replace this loop with a do-while loop
    
    { System.out.print(symbol);
    y++;}
    //end for loop
    
    
    
    
    else
    {System.out.print(symbol);
    for (int w = 2; w <= width-1; w++){
    System.out.print(" ");}
    
    System.out.println(symbol);}
    //end else
    {
    System.out.println();}
    }
    while (y = 1);
    }
    }
    }

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I think I am getting closer.. do I need to declare x and y as int variables? If I do where would I declare them at the beginning? I am now getting errors saying cannot find symbol for x and y.
    Best answer: try it and find out. If it doesn't work, try tweaking it. You'll have a much deeper understanding of all this if you play with your code a bit.

  7. #7
    hungdukie is offline Member
    Join Date
    Nov 2008
    Posts
    32
    Rep Power
    0

    Default

    Yes, you are right. I have been playing with it and now I at least get the program to compile without any errors but when I run the program instead of drawing a rectangle, it just endlessly prints 2 characters down the page side by side. I am not sure why it does that. My corrected code is:
    Java Code:
    x = 1;
    while ( x <= height)
    {
      {   System.out.print(symbol);
         x++;
      }  
    
     y = 1;
    do 
    {
      if (x == 1 || x == height)
        {System.out.print(symbol);
        y++;}
    	
    
      else
        {System.out.print(symbol);
      for (int w = 2; w <= width-1; w++)
        System.out.print(" ");}
    
      System.out.println(symbol);
    {
    System.out.println();}
    }
    
    while (y <= width);
    
    }
    }
    }

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Let me show you a trick. When I need to debug code like this, I'll shove some System.out.println's in there to tell me what's going on. Run this:
    Java Code:
    public class Fubar
    {
    
      public static void main(String[] args)
      {
        int x = 1;
        int y = 1;
        int height = 10;
        int width = 10;
        String symbol = "*";
        while (x <= height)
        {
          System.out.println("Location A: x = " + x + "; y = " + y);
          {
            System.out.print(symbol);
            x++;
            System.out.println("Location B: x = " + x + "; y = " + y);
          }
    
          y = 1;
          do
          {
            if (x == 1 || x == height)
            {
              System.out.print(symbol);
              y++;
              System.out.println("Location C: x = " + x + "; y = " + y);
            }
    
            else
            {
              System.out.print(symbol);
              for (int w = 2; w <= width - 1; w++)
                System.out.print(" ");
              System.out.println("Location D: x = " + x + "; y = " + y);
            }
    
            System.out.println(symbol);
            {
              System.out.println();
            }
            System.out.println("Location E: x = " + x + "; y = " + y);
          }
          while (y <= width);
    
        }
      }
    
    }
    This will tell you where the infinite loop is and what variable isn't being changed. Then you have to figure out why.

  9. #9
    hungdukie is offline Member
    Join Date
    Nov 2008
    Posts
    32
    Rep Power
    0

    Unhappy

    I'm still lost. I am using the same values as I was given in the original for statements. i really can't figure out what I have to do to fix this. I am guessing that the problem area is somewhere in the do-while statement but I don't understand what is happening versus what should be happening. Is there any way you can try to explain to me what is going on? I'm sorry I'm a newbie and I really am trying hard to understand this but I am lost. Thanks.

  10. #10
    hungdukie is offline Member
    Join Date
    Nov 2008
    Posts
    32
    Rep Power
    0

    Default

    Okay here is what I just did. I figured out that the reason I had an infinite loop was because I had the value for my boolean still set at y<=width and I changed it to y>width so now it isn't looping infinitely but I am still stuck with whatever else I need to change. Can you offer any more hints?

  11. #11
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Talking

    Okay, what I discovered here is that there is no replacement for digging through this do/while/for stuff one time - totally focused on nothing but getting it right one time.

    All a for loop ever was is a handy-dandy syntactic sugar for
    Java Code:
    int index = 0;
    final int limit = 100;
    while( index ++ < limit ){...}
    and that is all it ever was.

    The compiler would just construct the while() syntax for you, leaving you in sugarland with sweet dreams.

    The crude awakening would come when you discovered that the vars were not scoping correctly like one would think them to be.

    Then the next thing is to realize how exactly do{}while(); syntax functions. Eventually I arrived at a boilerplate coding style which I always use, even where I do not need it:
    Java Code:
    variable someVariable = Object.getValue();
    if( variable meets precondition )
    { 
        do
        {
            meat of the matter;// 
        }
        while( -- / ++ );
    }
    else
    {
         handle error if there is any such thing;///
    }
    and wrap the whole thing in exception handling.

    The result is that arrays are big end first because "--" can test on zero with the resultant logic being that zero based array indexing works correctly.

    Small, tight, code will keep you in a Sandbox. This is the breakout point, run full-tilt-boogie!
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  12. #12
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default Yes, x & y must be declared as ints

    I might be a little late with this (I tried to state it in one my posts below)...
    do I need to declare x and y as int variables?
    YES!!! you have to to specify the type of those variables. You indicated that you got the program to compile, so this might already be fixed (although I have not seen any code that indicates it except Fubarable's).
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  13. #13
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default OK... got it working

    While reviewing the different changes to the program (it was getting very confusing), I decided to go back to the original original code (the one with for loops) and see if it works. It does. So then I thought, if I had to do this task, how would I go about it ? The answer: piece by piece (like Jack The Ripper would have suggested).
    With all the suggestions and samples that you have received, this should be simple:
    • First, replace the first for loop with a while loop. Remember to put the x incrementer (x++) in the right place.
    • Run program and see if you get the same result.
    • If yes, then replace the second for loop with a do-while loop. Again remember to put the y++ in the right place. There is one last thing for this loop. This loop runs twice, so you have to reset the y variable to 1.
    • Run program and see if the result is what you expect.
    • If not, use the technics you have learned in this post.

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  14. #14
    hungdukie is offline Member
    Join Date
    Nov 2008
    Posts
    32
    Rep Power
    0

    Default

    I have tried moving the y++ to after each line in the do-while statement and it doesn't stop the program from looping endlessly. Also I am not sure what you mean when you say that I have to reset the y variable to 1. How do I do that? I am pretty sure the x++ is in the right position, the while statement is correct as is, is it not? Can I put the y++ after the else statement? I did try that and it outputs the character on one row endlessly across the page.

  15. #15
    Join Date
    Dec 2008
    Posts
    10
    Rep Power
    0

    Default I have my own question

    Alright, i was requested by my teacher to make a slot machine program that would print if he won or if he almost won, and if he wished to play again.
    the use of the letter Y as confirmation of the loop was requested but when i run the program the loop does not occur. i know the problem lies in the while command, but i don't know how to fix it. Please help (Its in French, because im in a french class sigh)
    import java.util.Scanner;
    import java.util.Random;

    public class Machine_a_Sous {

    public static void main(String[] args)
    {
    Random generator = new Random();
    Scanner scan = new Scanner(System.in);

    int num1, num2, num3;
    String answer;
    do
    {
    num1 = generator.nextInt(9)+1;
    num2 = generator.nextInt(9)+1;
    num3 = generator.nextInt(9)+1;

    if ((num1 == num2) && (num2 == num3))
    {
    System.out.println(num1 +"\t"+ num2 +"\t" + num3 + "GAGNANT! ");
    }
    else
    if (num1 == num2 || num3 == num1 || num3 == num2)
    {
    System.out.println(num1 +"\t"+ num2 +"\t" + num3 +"Presque!");
    }
    else
    {
    System.out.println( num1 + "\t"+ num2 +"\t"+ num3 + " Meilleur chance la prochaine fois");

    }
    System.out.println("Desirez-vous ressayez, si oui faite le Y");
    answer = scan.nextLine();

    }

    while (answer == "Y");

    }
    }

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Bernard, Please don't hijack someone else's thread as this is a rude thing to do. If you have your own question, please start a new thread and ask it there.

  17. #17
    Join Date
    Dec 2008
    Posts
    10
    Rep Power
    0

    Default Apology

    I apologize, thanks anyways

  18. #18
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default Case? ==?

    OK... two problems (well one is not so much of a problem really):
    • You can't compare strings with "==". Use the String class methods like equals, compare, etc.
    • The second problem (minor) is that your not taking into account the case of the answer. Again, use the String methods toUpperCase() or toLowerCase to avoid this problem. What happens if you change the while statement to?:

    Java Code:
    while (answer.toUpperCase().equals("Y"));
    Luck,
    CJSL

    Edit: I did not mean to answer Bernard's post in hungdukie's post... I apologize. I thought I was answering the OP's post. Sorry.
    Last edited by CJSLMAN; 12-07-2008 at 01:12 AM. Reason: OOOPPPSSS...
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  19. #19
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default Back to the original post...

    ok.... believe me... your code is probably looking pretty frankenstein right now after all the changes you have tried (I know... I've been there... done that). Go to my last post and do it as I indicated. It will be faster then if you try to do surgery on the code you have right now (and which you don't understand either).
    Go back to the code with the for loops and replace them with the do/do-while loops, one at a time. When one is working, move on to the next.
    You have nothing to loose, because you don't know what is going on (placing pieces of code at random spots in your code is not a good sign).

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  20. #20
    hungdukie is offline Member
    Join Date
    Nov 2008
    Posts
    32
    Rep Power
    0

    Default

    You're absolutely right I have made so many changes willy nilly to try to get this, right now I am now totally lost.
    I did only the first part, replacing the first for statement with a while statement. I know I have a problem because the output is not right. The code I tried was:
    {
    int index = 0;
    String symbol = " ";
    int height = 0;
    int width = 0;

    symbol = JOptionPane.showInputDialog(
    "You will be outputting a rectangle to the screen"
    + "\nEnter the character that you would like to use");

    height = Integer.parseInt(JOptionPane.showInputDialog("Plea se enter the height.\n"));
    width = Integer.parseInt(JOptionPane.showInputDialog("Plea se enter the width.\n"));

    System.out.println("Rectangle = " + height +" rows by "+ width + " columns");

    int x = 1;
    while (x <= height)
    {
    {
    System.out.print(symbol);
    x++;
    }

    {
    if (x == 1 || x == height)
    {
    for (int y = 1; y <= width; y++) //replace this loop with a do-while loop
    {
    System.out.print(symbol);
    } //end for loop
    } //end if

    else{
    System.out.print(symbol);
    for (int w = 2; w <= width-1; w++){
    System.out.print(" ");

    System.out.println(symbol);
    } //end else
    System.out.println();
    }//end for

    }
    }
    }
    }
    I also know now that my loop running infinitely is due to a problem with my do-while statement because with the for statement in this code the only issue is the output not an endless loop.
    I tried placing the while statement in braces and that didn't work. Is it a problem with the value of the loop control variable? I don't know. I feel like I'm grasping at straws here. I'd appreciate any other tips or advice.
    Here is what the output is looking like:

    Rectangle = 3 rows by 5 columns
    kkkk k
    k
    k

Page 1 of 2 12 LastLast

Similar Threads

  1. How to speed sql Statements?
    By bezudar in forum Advanced Java
    Replies: 3
    Last Post: 11-20-2008, 10:53 AM
  2. Need help - using algorithm statements
    By javanewbie in forum New To Java
    Replies: 2
    Last Post: 07-23-2008, 12:20 PM
  3. avoiding if statements
    By valoyivd in forum New To Java
    Replies: 1
    Last Post: 04-02-2008, 10:08 AM
  4. Help with actionPerformed Statements
    By wco5002 in forum New To Java
    Replies: 8
    Last Post: 03-26-2008, 05:02 AM
  5. Help with if else statements
    By zoe in forum New To Java
    Replies: 1
    Last Post: 07-24-2007, 08:56 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •