reset password
Author Message
khsu
Posts: 30
Posted 13:54 Feb 14, 2014 |

Udacity does not explain the usage of boolean with loops. The classnote vaguely explains it, I do think this needs to be elaborated.

 

Can we get a sample code with the usage of boolean in loops?

rabbott
Posts: 1649
Posted 14:42 Feb 14, 2014 |

You can use the Scanner method hasNextInt( ) to determine when to terminate the loop. The easiest way to do that is to read the user's into all at once into a String and then read the numbers from the String

Translate 

Set a Boolean variable "first" to be true.

while another value has been read successfully

{

if first is true

Set the minimum to the value.

Set first to be false.

else if the value is less than the minimum

Set the minimum to the value.

}

Print the minimum. 

into

// Prompt the user to enter a line that contains all the inputs

           System.out.print("Please enter a series of integers on one line: ");

           Scanner scanner = new Scanner(System.in);

           String numbers = scanner.nextLine();  // Read the line into the String numbers

           scanner = new Scanner(numbers);       // Create a new scanner that reads from numbers

//  Set a Boolean variable "first" to be true.

while (scanner.hasNextInt())      

{

// read a value from the input

// if first is successful

// Set the minimum to the value.

// Set first to be false.

// else if the value is less than the minimum

// Set the minimum to the value.

}

// Print the minimum. 

 
Last edited by rabbott at 14:44 Feb 14, 2014.
khsu
Posts: 30
Posted 15:13 Feb 14, 2014 |

What I meant as a sample was a working example of a program using the similar method suggested.

What I am having trouble right now is understanding what "values" and "minimum" are suppose to represent in this exercise.

rabbott
Posts: 1649
Posted 19:41 Feb 16, 2014 |

"Values" means the values you read from the input. "Minimum" means the smallest of those.  But you must already know that. Besides that, I don't understand what you are asking.  The assignment is for you to write a working version of the assigned problem. I've already written a lot of it. It's up to you to translate the rest into Java. Read the code in the message above and try it out by hand on some examples. That should help.

Last edited by rabbott at 19:44 Feb 16, 2014.