3164

Why is my loop skipping this conditional?

Question:

Time for my daily newbie Java question :-D

I must not be understanding conditionals in a while loop correctly.

I have this:

while (true){ if (){ ... } else { ... } if (){ ... } else { ... } if (SENTINEL){ break; } }

The first if/else statement is working, and the sentinel is working, but the second if statement gets skipped. If I flip the first and second if statement, then the first if statement still always gets executed and skips the second. What am I missing?

Can I have two if/else statements in one block like this?

I'll include the whole code, though it's pretty ugly, and I'm sure I'll get lots of people telling me better ways of doing this. I don't mind learning better ways, but for now, I just want an answer to this looping question. thanks!

public class FindRange extends ConsoleProgram { private static final int SENTINEL = 0; int value = 0; int highNumber = 0; int latestValue = 0; int lowNumber = 0; public void run() { addNumbers(); } private void addNumbers(){ value = readInt("Enter number:"); while(true){ if (value == SENTINEL){ break; } latestValue = readInt("Enter number:"); getHighNumber(); getLowNumber(); if (latestValue == SENTINEL){ break; } } println("High Number is "+highNumber+"."); println("Low Number is "+lowNumber+"."); } private void getHighNumber(){ if (latestValue >= value){ highNumber = latestValue; }else { highNumber = value; } } private void getLowNumber(){ if (latestValue <= value){ lowNumber = latestValue; }else { lowNumber = value; } } }

Answer1:

Are you trying to find the minimum and maximum of a series of numbers? If so, you should definitely use Math.min() and Math.max(). It's much clearer that way and you can do away with the if statements. It's also simple enough to do it in the loop with local variables instead of fields.

The common idiom is something like this:

minValue = Math.min(minValue, candidateValue); maxValue = Math.max(maxValue, candidatevalue);

Answer2:

It's possible that the behavior you're seeing comes from the fact that you are always comparing the latest value to the initial value. The initial value will never change-- so if you put in the following input:

20, 60, 50

the high value that gets reported would be 50. That's because 50 is the most recent value to be greater than 20. I think you probably mean to compare the latest value to the high value, no?

Answer3:

You can definitely have 2 if/else blocks within the loop; however if your sentinel gets hit the loop will exit.

Posting the entire block would help.

<hr />

What will happen (after reading the posted code) is when any new value you enter within the loop is greater than the original value, lowNumber is set back to the original. So for example if your input is: 7 6 5 8 Your corresponding low number values will be: 7 6 5 7 Which is incorrect. What you could do is toast the "value" variable altogether, set your low and high to the original value, then compare latest with low and high in the get* methods.

Answer4:

Shouldn't you be setting value = latestValue at the bottom of your while loop?

Value never gets updated after the initial read... maybe something like this:

public class FindRange extends ConsoleProgram { private static final int SENTINEL = 0; public void run() { addNumbers(); } private void addNumbers() { int value = 0; // Set this to highest possible value int highNumber = Integer.MIN_VALUE; // Set this to lowest possible value int lowNumber = Integer.MAX_VALUE; while (true) { value = readInt("Enter number:"); if (value == SENTINEL) break; lowNumber = Math.min(lowNumber, value); highNumber = Math.max(highNumber, value); } println("High Number is " + Integer.toString(highNumber) + "."); println("Low Number is " + Integer.toString(lowNumber) + "."); } }

Recommend

  • Adjusting R Markdown Title Position in PDF output
  • Serialization list of different object
  • Why does Python write one wrongly encoded line every two lines?
  • How to read UDID, Major, Minor of beacon on android devices?
  • Odoo 10 : Custom module doesn't appear in top black menu after installation
  • How to add row to table when enter key press using Jquery?
  • Error Google LineChart with proper (?) JSON format
  • Android L Developer Preview packages missing?
  • How to enable httpsrc plug-in in my gstreamer?
  • PowerShell Flatten Directory Structure
  • pb nagios bash script null result in if
  • Why does [[ -eq ]] show non-numerical strings as equal in Bash?
  • Writing a string at a given position in a drawing in Codename one
  • how can iOS app set the Core Bluetooth advertisement rate?
  • Bash convert string to timestamp
  • How to recursively resolve symlinks without readlink or realpath?
  • DynamoDb “Query key condition not supported”
  • Create registry key in 32-bit hive on x64 PC using Installshield 2012 LE - Avoid redirection
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • Stop Bash Script if Hive Fails
  • how to adjust image in a panel in Java swing?
  • how to do an event when i swipe from fragment to the other
  • Possible to stop flickering java tooltip in heavyweight mode?
  • sending/ receiving email in Java
  • Javascript + PHP Encryption with pidCrypt
  • Akka Routing: Reply's send to router ends up as dead letters
  • Arrays break string types in Julia
  • How to delete a row from a dynamic generate table using jquery?
  • WPF Applying a trigger on binding failure
  • Proper way to use connect-multiparty with express.js?
  • JTable with a ScrollPane misbehaving
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Getting Messege Twice Using IMvxMessenger
  • Java static initializers and reflection
  • unknown Exception android
  • Checking variable from a different class in C#
  • Sorting a 2D array using the second column C++
  • How can i traverse a binary tree from right to left in java?
  • java string with new operator and a literal
  • How can I use threading to 'tick' a timer to be accessed by other threads?