• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can you test loop condition within a loop?  RSS feed

 
Marius Semeon
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way to use a loop such that once the original conditional is no longer met, the rest of the code within the loop is not executed? For example in:

I would like to make it so that if you ran the method the only code that would be executed would be SOME CODE 1 and SOME CODE 2. Instead though, all the code within the block is ran and the condition of the while loop is only checked afterwards.

I realise one solution would be to use 'if' statements after each segment of code within the 'while' loop, followed by 'break' statements depending on if the condition is met. Something like this:


This works but it seems really messy and inefficient so I imagine there must be a better way. I have 30+ different segments of code I want to implement within the while(x<num) loop and it is a pain to have to write individual 'if' and 'break' statements after each one.
 
Pete Letkeman
Ranch Foreman
Posts: 914
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marius Semeon wrote:I have 30+ different segments of code I want to implement within the while(x<num) loop

30+ lines is one thing, but 30+ different segments. I think you may want to look into refactoring your code, if possible.
Some people have a rule that when you go past X lines of code, then your method is doing too much and you need to refactor it.

As far as testing within the loop, I think that you have the simplest solution with the if and break statements.
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course you can test loop variables inside the loop. But why? What sort of code are you writing that requires such complicated control structures? That looks like very dubious design to me. What is more, you haven't supplied any sort of precondition for that method, nor any sign of enforcing it. What values of num are permissible? What is going to happen if I pass 2147483647 as an argument to that method? Do you actually want a loop at all?

You can have nested ifs.At which point, I hope the arrowhead shape of the code will have all the other mods telling me off for poor code style. You can use switch‑case with fallthrough:-Again, the weird control structure shou‍ld make you suspicious about your design.
 
Marius Semeon
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pete Letkeman, I am very new to programming and was not aware of that rule people abide by, thanks for letting me know. As for refactoring; have read and watched some tutorials on it, seems like good programming practice.

Campbell Ritchie, as for enforcing a reasonable range of values for the argument, I will definitely do that, just haven't shown it here as didn't seem pertinent to the question. You are probably right though in that my design is likely very dubious, perhaps you could tell me where I am going wrong design-wise? It basically all comes down to the fact that you cannot dynamically name variables in Java. I have an Animal class and I want to be able to instantiate a large number of Animals in main() and populate a virtual landscape with them so I don't have to do it individually like so:
etc etc..

Very tedious, and means that if I wish to run the program with a different number of Animals, I'd have to manually go about adding new ones rather than using a general generateAnimals(int num) method which generates and randomly places anywhere between 1-26 animals on my grid. Were it possible to dynamically name object reference variables, my generateAnimals(int num) method could simply utilise a for loop to instantiate new Animals, give them a reference variable name dependent on the value of 'num' and allocate them a random position on the grid.
I realise I can do the same thing without giving them names ie something like:

But then I am left with no ref variables pointing to my Animals and thus cannot do anything with them, like move(), eat() etc etc. That's why I feel defeated and am resorting to the very ugly, longwinded, and poorly designed method of using endless 'if' and 'break' statements. Something like:


I'm sure it's terrible design but it's the only way I know of where I can create them all in bulk when running the program and retain a reference for each Animal object.

 
Pete Letkeman
Ranch Foreman
Posts: 914
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marius Semeon wrote:Pete Letkeman, I am very new to programming and was not aware of that rule people abide by, thanks for letting me know.

This is more of a guideline then a rule. Everyone one seems to have their own value for X and some companies enforce this.

As for being new, well let me welcome you to CodeRanch, even if you have already been welcomed.
You will find that there are many people with many different levels of experience.
Some people here are very well versed in programming and in Java.
I've found that everyone here has been helpful, welcoming and respectful as well.

One thing that we all have in common is we all started with doing something like printing "Hello World" to the screen.
So do please not be intimated with programming.
 
Fred Kleinschmidt
Bartender
Posts: 571
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way similar to Campbel Ritchie's, but using switch WITH breaks:
And the the coded for the go() method could be

The option methods could also be put in an array or ArrayList so go() would be more like:
for ( int i=0; i < num; i++ ) {
   optionMethods.get(i).execute();
}
where each entry of the optionMethods ArrayList is an instance of a class that implements some Interface that defines the execute() method.
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It probably looks better to create multiple Animal instances, with or without randomisation. You can of course store all the references in an array, a List<Animal> or similar.

I do not like arithmetic with Math#random; if you look at this old post and the other links in it, I explained why there. (Last bit copied from my post in June.)
 
Marius Semeon
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pete Letkeman, thanks man - yes everyone seems very friendly and helpful here, feels like a much chiller environment than something like stackoverflow I have to say, a lot more patient and less punishing for not framing a question 100% correctly/according to guidelines. I'm not completely new, been reading and practising in my spare time for the past 5 months, but have no background in computer science or similar so progress is rather slow with just a book and online tutorials (been thinking about enrolling on a MOOC which I guess would speed it up).

Fred Kleinschmidt wrote:
Another way similar to Campbel Ritchie's, but using switch WITH breaks:


Fred Kleinschmidt- thanks. Using switch allows me to omit all the if statements so makes it less messy.
 
Marius Semeon
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:It probably looks better to create multiple Animal instances, with or without randomisation. You can of course store all the references in an array, a List<Animal> or similar.
I do not like arithmetic with Math#random; if you look at this old post and the other links in it, I explained why there.


Yes I will add the references to an Animals array.

Thanks, I have been using both Random's nextInt() function as well as the Math class to generate pseudorandom numbers but wasn't familiar with IntStream. Will have a closer look now to start using it.
 
Pete Letkeman
Ranch Foreman
Posts: 914
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marius,

There are some books and resources listed and reviewed here:
https://coderanch.com/c/books
Note:
  • not all of the material listed in the books section is books, some could be videos and other tutorials.
  • not all of the material listed in the books section is related exclusively to programming in Java.

  • Some people may think/suggest that IntStream is more of an intermediate or advance class as it has to do with streams and stream processing.
    If that is the case, then it may not recommended for those who are new.
     
    Campbell Ritchie
    Marshal
    Posts: 56595
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Pete Letkeman wrote:. . . IntStream is more of an intermediate or advance class . . . .
    There are people who think the Stream API is an advanced topic, but I think at least the simpler uses of Streams shou‍ld be taught early in courses, i.e. it is a beginner's topic.

    Using IntStream#range or Random#ints or similar to create arrays is probably simple enough to be taught in a beginner's course, and it looks much neater than using a for loop as I had to use when I was starting.
     
    Pete Letkeman
    Ranch Foreman
    Posts: 914
    26
    Android Chrome IntelliJ IDE Java MySQL Database
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:but I think at least the simpler uses of Streams shou‍ld be taught early in courses, i.e. it is a beginner's topic.

    You are 100% correct and there is no disagreement here.

    Marius did say he was going to look into using IntStream and I was trying to warn him that this could be an advance topic.
    Marius also stated they that he only recently started programming so I did not want to scare him off with an advance topic.
     
    Campbell Ritchie
    Marshal
    Posts: 56595
    172
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    When I went around singing at concerts, John who led the choir said it is easy to get children to sing difficult music. Very easy. All you have to do is not let the find out it is difficult.
     
    Marius Semeon
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Pete Letkeman wrote:Marius,

    There are some books and resources listed and reviewed here:
    https://coderanch.com/c/books


    Thanks, I'll probably get a new book soon, have got about 60% of the way through Head First Java 2nd Edition, but keep going off on tangents making my own projects along the way, experimenting different things and looking up problems as I encounter them.
     
    Pete Letkeman
    Ranch Foreman
    Posts: 914
    26
    Android Chrome IntelliJ IDE Java MySQL Database
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Marius Semeon wrote:but keep going off on tangents making my own projects along the way, experimenting different things and looking up problems as I encounter them.

    This happens to me as well .

    I provided the link for you not because you need a book, but because you said you were new to this.
    Please note that are plenty of other resources aside from here the ones listed https://coderanch.com/c/books.
     
    Campbell Ritchie
    Marshal
    Posts: 56595
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Marius Semeon wrote:. . . experimenting different things and looking up problems as I encounter them.
    I think that is a very good way to learn programming
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!