Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Extracting a value from a while loop after each iteration  RSS feed

 
Eirik Lauritsen
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello! I'm trying to make this program print the average number of steps after 100000 iterations, but i'm having some issues saving the number of steps after each repetition of the while loop.
I know that i have to make a value that divides the total number of steps over 100000 iterations by the number of iterations and print that at the end, but I don't see any need to make that before i figure out how to extract the steps value after each iteration

 
Carey Brown
Saloon Keeper
Posts: 3310
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need
  • a variable sumOfSteps
  • set steps to zero before entering while loop
  • after while loop add steps to sumOfSteps
  •  
    Carey Brown
    Saloon Keeper
    Posts: 3310
    46
    Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Also
    xLocation and yLocation should be reinitialized before the while loop.
     
    Eirik Lauritsen
    Greenhorn
    Posts: 19
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks for the help! Now I ended up with a code that looks like this. Are there any changes that you would make? I'm new to the world of Java so still in the learning process

     
    Carey Brown
    Saloon Keeper
    Posts: 3310
    46
    Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Line 39 should be
    Line 40, calculating the average should be done outside of the for() loop.
    Before line 18 initialize steps to zero.
    Math.random() has been replaced by the Random class. Use:


     
    Carey Brown
    Saloon Keeper
    Posts: 3310
    46
    Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Note the operator "+=".
    A = A + B
    can be more succinctly written as
    A += B
    So, you should write
    xLocation += west;
     
    Carey Brown
    Saloon Keeper
    Posts: 3310
    46
    Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I merged your stuff with the following thread. I hope that is okay by you.
     
    Eirik Lauritsen
    Greenhorn
    Posts: 19
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I'm trying to move the part within the for statement to it's own method, but i'm unsure about how to do this. The first thing that strikes me is that copying and pasting it should do the job, but then i'm getting problems with the values not beeing defined inside the new method. How can i work around this?

     
    Carey Brown
    Saloon Keeper
    Posts: 3310
    46
    Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    First of all, you need to get your code to work. You have ignored some of my suggestions.
     
    Eirik Lauritsen
    Greenhorn
    Posts: 19
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    That's my bad on the thread, didn't see your suggestions before I posted it :/ Now, i followed you suggestions and ended up with a code that looks like this, how would you go about to create a method of everything inside the for statement now? I know that i have to copy the current code and replace it with the name of the new method, but I get stuck there. DO i have to move alle the variables down to the method so it can reach them?

     
    Liutauras Vilda
    Sheriff
    Posts: 4917
    334
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Eirik Lauritsen wrote:I know that i have to copy the current code and replace it with the name of the new method, but I get stuck there.

    You don't have to, but that would be a way way better approach than you have now.

    Methods are the tools, which supposed to help you to deal with the complexity of the task, so you wouldn't solve whole task at once, but rather you could decompose it to a smaller tasks, so you could deal with less problems at a time. In fact, with one problem at a time.

    What do you think, how many tasks which are sort of disconnected from each other you are solving at the moment? Don't think about this question which requires definite answer, it is for you just to think about.

    Very possibly, that each loop (while; for) they represent some process which happening, for example:

    This example is just to demonstrate what I meant by word decomposing.
    Each method supposed to be responsible for one and only one clear purpose. It might be readLine(), it might be defineLocation(), it might be recordRoute()... et cetera.
     
    Eirik Lauritsen
    Greenhorn
    Posts: 19
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I understand why I should use methods and I guess it's especially useful when the programs get even more complex so you don't clutter the code with too much information at once. Right now i would say that inside the for statement i have one part that initialises and resets the location and steps after each iteration of the while loop. One part that generates a random number and then uses it to determine the new value of xLOcation or yLocation, it repeats this until either x- or yLocation goes outside the boundaries. After this it adds the number of steps to the sumOfSteps and starts over again.

    Seeing as I haven't properly learned how to write methods i'm looking for some guidelines on how to do it in this program. So if you're able to give me any pointers it would be much appreciated

     
    Campbell Ritchie
    Marshal
    Posts: 56529
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Eirik Lauritsen wrote:. . . methods [are] especially useful when the programs get even more complex . . .
    No, you shou‍ld be using different methods in even the simplest of programs. If you enhance something simple like hello world to be properly object oriented, then you can use several methods to get this sort of code to work:-
    System.out.printf("Hello, %s :‍)%n", getName());Your last post lists several method which you shou‍ld be using, although you may not have noticed that. You say you want to create a random number: in that case create a random number method. You may later decide to revert to simply writing myRandom.nextInt(123), but use a separate method for the time being. Then you are moving in the x axis, or the y axis. Those mean you want methods moveHorizontally(...) and moveVertically(...).
    You can use methods to verify whether your x and y positions are still within your limits.

    You may decide you could have done it differently, but you now have suitable methods. If you find yourself writing things like this, however:-. . . you are repeating code in lines 4 and 6; you shou‍ld recognise that as a danger sign telling you to create a moveHorizontally(...) method. Yes, it would be better to write moveHorizontally(randomX);...moveHorizontally(-randomX);
     
    Junilu Lacar
    Sheriff
    Posts: 11477
    180
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Here are some guidelines for writing code that makes better use of methods:

    1. Break things down into smaller tasks. Create methods for each small task.

    2. Keep the scope of variables as small as possible. Declare them as close as possible to the section of code that actually uses them.

    3. Try to use names that explain what something is for, i.e. use names that reveal intent.

    4. Prefer to use parameters to provide information rather than globally accessible values.

    Let's ignore the fact that you have written largely procedural code even though Java is supposed to be an object-oriented language. Unfortunately, most students are taught to start from a procedural programming perspective and it appears the case with you so let's just go with that for now.

    All your code is in the main() method. That's a pain and it violates the first guideline above.  The main() method should be small and it should just give you an overall picture of what's happening in the program without giving away every single minute detail of the implementation.  Here's an example of what your main might look like after some refactoring:


    This version of main() follows the guidelines: it's small, only 2 lines of code, it calls methods that are named in a way that explains what they do, and there is only one variable in scope, averageSteps. The parameter being passed to the runTrials() method is a constant value that is assigned the symbolic name of NUMBER_OF_TRIALS, which again tells you a lot about what it represents and is more descriptive than the generic ITERATIONS.

    The amount of time it takes to understand what this program does at a high-level is about the amount of time it takes to read the code itself. This is how I would read this code: "Run a certain number of trials and get back the average number of steps for each trial. Then report the results."

    That's it.

    Now, can you figure out what the rest of the code would look like if you had a main like this? All the code that you wrote would still be valid except it would be factored out between the two methods called by main().

    Your main blocker in successfully breaking up your code is that some of your variables have too big of a scope.  If you examine each variable and move it closer to where they are actually needed, it will be easier for you to find clumps of code that can be extracted to their own methods. Give it a shot first.
     
    Eirik Lauritsen
    Greenhorn
    Posts: 19
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks for the desriptive replies, will try to implement your guidelines into my coming programs, learning by doing i guess. Do you have any tips on how to practise methods or should i just write programs and then restructure them so it includes different methods?
     
    Junilu Lacar
    Sheriff
    Posts: 11477
    180
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Why wait to practice on future programs? Your current code is perfect for practice now.

    As for where to start, I'd say it's different for everyone and even for one person, it can be different for each case. Sometimes it's easier to start with a detailed implementation and just get it to work, then restructure. Sometimes, starting from high-level method and slowly drilling down to progressively smaller/detailed methods is faster.
     
    Knute Snortum
    Sheriff
    Posts: 4274
    127
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I often start writing programs like this:
    See what I'm doing there?  I have comments for the high-level tasks I need to do.  Nine time out of 10, each comment is a method.  So let's say the first task is a method:
    See how method building comes naturally like this?  You may have some problems with returning data and passing data to other methods, but we can go over that more when you run into it.
     
    Liutauras Vilda
    Sheriff
    Posts: 4917
    334
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Eirik Lauritsen wrote:Do you have any tips on how to practise methods or should i just write programs and then restructure them so it includes different methods?

    I believe practice is important and key here, and better quality comes with extensive amount of experience. I'm unsure you formulating second half of the sentence correctly. To me sounds like, you write program in whenever way it goes, then you just adding different methods because: you just have to, somebody told that, heard of them they are useful...

    Methods should come I believe from common sense. When you get a task to slice the bread, you know exactly what you need - a knife (maybe a special kind of it). If you were given piece of raw tin or metal material you might would be able to achieve the task too, but would be that comfortable? Would make sense?

    Now you have knife. You don't stuff methods just because you have to, you create them and re-use them whenever you see they make sense. What they do, they hide from you the raw tin or raw metal material, and instead, they give you a name "knife", which on its own gives you a pretty good idea what you can do with it without even seeing him.

    Same with your code. Your code currently is pretty simple, and at the same time pretty confusing, because it isn't straight forward for a regular human eye.

    To be honest, I don't even know the whole goal of your program, because your class is named "MojangDel4". Class represents an idea of a Kitchen, where knife could be found. So when you hear somebody saying Kitchen, you would be pretty confident you'd find the knife there if needed, plates, cooking machine and similar. Now, what's about MojangDel4? By the way, I thought there is 14 at the end, it seems only 4 with a prefix of l.

    So first - name class properly, that is the starting point in your case I'd say. What this class represents, some kind of game? Name it SharkGame, it is still tells nothing - but we know it is a game and might be even fun! Write nice comment above the class name in a format:
    So you and the reader know the rules and gets primary idea what is the game about.

    Then look down into methods. You have lots of if/else if, maybe there would make sense having a method move()? moveEast(), moveWest(), moveNorth(), moveSouth(). Noticed? move move move... When you see something like that, you can get an idea, that might addition of parameter would allow having only moveTo(Location). And then we go back to object-oriented programming.

    Have you been mentioned about objects in your course yet? Which year of course you are in? This exercise is actually quite difficult to solve in procedural way, because you can't wire separate pieces properly as they don't have much meaning.

    Will continue later... got to go now..


     
    Eirik Lauritsen
    Greenhorn
    Posts: 19
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I started the class about 1 month ago, so we're still learning the basic functions and methods of Java. This task was divided into 5 parts and and each part added something new to the code. Started with just the xLocation and slowly added new parts to the code. I guess it would come more naturally if I started with the complete program, but as we have to hand in 1 program for each part it's structured like this. It's more like 5 small programs turned into 1 bigger rather than 1 program fractured into smaller part. That's why i'm trying to ask people that know more than me so they can guide me and give tips on how to improve
     
    Liutauras Vilda
    Sheriff
    Posts: 4917
    334
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Eirik Lauritsen wrote:I guess it would come more naturally if I started with the complete program, but as we have to hand in 1 program for each part it's structured like this.

    No, it wouldn't, but many think exactly like that. But the skill you need to acquire, is how to add functionality gradually as this is what's happening in real. How easy is going to be to do so is the one of the key factors.

    Eirik Lauritsen wrote:This task was divided into 5 parts and and each part added something new to the code.

    Oh dear. Would be wonderful assignment if there were 5 parts, where 1 of those would have been to write and submit a Location class. Then another part to write a Direction class (enum). Then another part, to write Player class and submit that separately. And then... And then finally the part to submit whole wired and working program. But it might will come in later years. Month ago is quite recent, so hope is still there.
     
    Junilu Lacar
    Sheriff
    Posts: 11477
    180
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    My advice to you would be to try different ways of approaching the problem. I don't think the way you're being asked to do it is very effective.  First of all, it results in what we call a Big Ball of Mud -- a bunch of different things all jammed into one method. That approach not only complicates your code and makes it more difficult to understand, it makes the code more brittle and more likely to hide bugs. You've already tried it the way your teacher wants you to do it, so try it the way folks here have been suggesting.  The way Knute and I are suggesting demonstrates what's called "functional decomposition."  You start with the big idea of what your program should do, then slowly drill down to the smaller parts.

    For example, I showed a main() method that called a runTrials() method, right? What do you suppose the runTrials() method looks like? Something like this probably:
    (Edited: the method should be static since the previous related example had a call from a static context)

    Do you recognize any of that from what you wrote before? Do you see how at this level, you really only need to concern yourself with the steps variable? Do you see how the scope is limited to exactly the lines of code that need it?
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!