Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Finding max value using if an while

Greenhorn
Posts: 5
Hello. What I've been trying to do is compute a hailstone series which is if the user input is even it will equal (answer=x/2) and if it is odd it will equal (answer=x*3+1) until it reaches 1. What I'm trying to do is find out the max value using only if and while statements and I can't seem to figure it out yet after playing around with it. This is what I have so far.

any ideas?

Marshal
Posts: 57499
175
you should indent your code better, and leave spaces around binary operators. That makes it much easier to read.

You need to go through the loop with a pencil and paper, and check all the places where there are > and < comparisons. Check carefully what you are comparing with. What are the values of valueX and maxValue when you do those comparisons?

Sheriff
Posts: 23297
46
What is the "valueX" variable for?

And why aren't you considering all the elements of the series when you're looking for the largest element?

Sheriff
Posts: 21208
87

Paul Phoenix wrote:

That's not doing what you expect. If x is even then it will be divided by 2. If it's odd it will not be multiplied by 3 and have 1 added; it will be multiplied by 3, have 1 added, and then again be divided by 2.

If x is odd (x % 2 == 1) it will be multiplied by 3. That gives another odd number. 1 is then added, making the number even. You then check if x is even (x % 2 == 0) which it will now always be; if it was even before it wasn't changed and if it was odd it's even now.

I think you want to use an else instead:
That still gives you a result of 20 though. The 52 you are looking for will be the value of x after one loop iteration. But x != 1 so it will try again, halving the 52 into 26. It will then try again, again halving, etc.

Campbell Ritchie
Marshal
Posts: 57499
175
Yes, there are two errors in that bit of code, and I only noticed one of them.