Win a copy of Java Challengers this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • paul wheaton
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • Mikalai Zaikin
  • Himai Minh

if else selection in Java

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello folks!

I am struggling with some code. I have a variable that is required to change every time a method is invoked. I need the sequence to output the values 0 then 1 then 2 then 3 then 2.
I have managed to write an if statement that changes the integer from 0 to 1 and then I have used else if statements to change the integer to 2 then 3 then back to 2. Can anybody help me to change the integer to 0 upon the first loop? The integer is initialised to 0.


 
Martin Gerard
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
my code has the following structure:

 
Saloon Keeper
Posts: 8093
71
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Requirements are a bit vague. This would give you: 0 1 2 3 0 1 2 3 0 1 2 3
 
Marshal
Posts: 72657
317
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

You can't call a variable boolean because that is a keyword. You will have to call it something else. I don't know what it means so I shall make it very simple: b.
Don't write == true or == false. Both are poor style and very error‑prone; we see lots of people who write = by mistake.
Never if (b == true) ... please.
Always if (b) ... please.
Never if (b == false) ... please.
Always if (!b) ... please.
You can of course add an && somethingElse to the above formulae. Like this:- if (b && integer == 3) ...
Use integer++; or integer--; because both are simpler than what you wrote. The ++ and -- operators are in common use.
You might not need an if to make numbers cycle if you can work out a pattern or formula for the cycling.
 
Campbell Ritchie
Marshal
Posts: 72657
317
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Carey Brown wrote:. . . 0 1 2 3 0 1 2 3 0 1 2 3

You can get that without an if. You need the ++ and % operators. Or even ++ and bitwise and (=&). But I don't think that is the pattern MG wanted.
 
Carey Brown
Saloon Keeper
Posts: 8093
71
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Never compare a boolean to true or false directly. Example:
The reason is that you could accidentally introduce a bug if instead of  "==" you had put "=" which would then be an assignment.
 
Saloon Keeper
Posts: 23540
161
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We don't have any complaints about what forum you posted in (we'd move it, if we thought there was a better choice).

But all your edits were really confusing.

Please don't edit stuff unless you've spelled something unintelligently badly (like me). Making code appear and disappear, adding/removing basic questions, and other stuff like that should not be done in edits. If you've got a major change, re-post it with the changes in it.

Yes, I edited this. My spell checker changed "unintelligently" to "intelligently". Which is the sort of thing I was talking about, as it happens.
 
Saloon Keeper
Posts: 12893
280
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've reverted the last change.
 
Ranch Hand
Posts: 80
3
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The pattern is 0, 1, 2, 3, 2, repeat. I would go with a Dequeue like a LinkedList: pop from top and peek into bottom (wait, sorry, that didn't end up as planed).
It's like a deck of cards: You take the first from top and put it back as last on the very bottom. This way you end up with a repeating cycle with any length and order you like.
 
Campbell Ritchie
Marshal
Posts: 72657
317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Matthew Bendford wrote:. . . Dequeue . . .

What a good idea. Did you mean a Deque or its supertype, a Queue? I think both will work.You can do more or less the same with an array:-The 0, 1 at the beginning of the sequence are awkward, causing repeated code. Getting Carey's sequence is much easier:-The trick with &= 3 only works as a substitute for remainder by an exact power of 2.
 
Matthew Bendford
Ranch Hand
Posts: 80
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Did I misspelled it again? Dang it!
But yea, as we go for a simple FIFO I guess any simple Queue will be ok. I'm just very used to LinkedList as in my last projects I used both FIFO Queues as well as LIFO Stacks - which both easy provided by Deque and its implementing LinkedList.
I'm aware that there're maybe other implementations, but as I only rarely require random access but rely on sequential access way more often I'm ok with its bad random access performance, as it has better sequential performance than something array based which fits my needs better. Hence I'm just used to use LinkedList pretty much all the time instead of other collection types (unless I have to like a Map).
In my eyes whenever there's a repeating cycle which require to maintain its overall initial order in a loop I don't think about it anymore but just put in some Deque<T> someDeque=new LinkedList<>() - it just became a (maybe not always the optimal) habit. Pretty much like my "addiction" to interfaces.
 
Campbell Ritchie
Marshal
Posts: 72657
317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As an implementation, ArrayEeque will give you the equivalent of a circular array, so I think it will execute faster than a linked list. I think a plain simple array might be easier to write however.
 
Saloon Keeper
Posts: 4380
163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also possible is to have a running total and a delta that gets added to total in each step. Afte every three steps change the sign of delta.

But hey: this is a periodic function, so the very first thing that comes to mind is a Fourier series.      
 
Matthew Bendford
Ranch Hand
Posts: 80
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Cambpell
Well, at least to my (maybe wrong?) knowledge anything array based always require a lot of copy things around on even small changes. I'm not aware if Javas array implementation is smart enough to just move some pointer instead of create a new array, copy all except the first/last over and free the old one. As for LinkedList all that change are a few references. Depending on size of the Deque this can make quite a difference between just change a few references or move a bunch around in memory.
I'm aware that array based collections always will have an advantage in respect to random access - but as indexed random access rarely occur in my current code to me that's negligable.
But I guess this goes too deep into micro-optimization that only starts to become significant at quite a huge number of data that gas to be processed - in which case I guess it might be a more useful way to inspect possible parallelization.
 
Campbell Ritchie
Marshal
Posts: 72657
317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don't go on about pointers and freeing memory. All pointers are hidden behind references, and the JVM does automatic garbage collection, so you can only get memory leaks if you retain unwanted references. [edit]The preceding applies only to Java®, not to C/C++.
Agree that arrays are very mutable, but so are Lists and Queues. In all cases you would need to keep a tight grip on the references, and I suggest they would need to be local variables with no possibility of their escaping the method. [Actually the JVM does escape analysis on local variables; if they never escape their method, local variables can all be created on the stack rather then the heap, and all the memory they occupy is regarded as free for overwriting whenever the method completes.] There are methods in the Arrays class which can do exactly what I think you mean, copying part of the array.
Once the array deque is full, its capacity won't change. It works as a circular array (I think). You have an index where you add things and an index where you remove things. The two follow each other along the array, remove() leaving a trail of nulls behind itself, until they reach the end of the array. Then they undergo a % values.size operation and return to the start of the array. Arrays can give faster micro‑execution than linked lists because there is no need to create a node object; it is only necessary to assign to the next available array index. You will only notice problems if the size of the queue changes (remember I am in Britain; we learn about queues with our mothers' milk) and it is necessary to copy the contents of the array into a larger array.
 
Matthew Bendford
Ranch Hand
Posts: 80
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yea, I guess I completely missed the most obvious approach: Use an array, fill it with the sequence and just have an index incrementing modular the arrays size. Sorry about that - I way overshot that really simple task with way too complicated oop based stuff.
As I'm not familiar with the Streams api I guess someone can come up with an even fancier functional approach than an oop or procedural one.

~ back to the studio
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic