Results 1 to 10 of 10
  1. #1
    Mike Miller is offline Member
    Join Date
    Sep 2011
    Posts
    4
    Rep Power
    0

    Default Sentinel value in a while loop

    Hi all,

    I'm trying to come up with a program that uses a sentinel value (in my case, it's zero) to stop a while loop that adds up integers. This is what the program is supposed to do:

    1. Prompt the user to input for a number (not necessarily a positive one)
    2. Get the user's input
    3. If the user's input is zero, the program quits. Otherwise, keep collecting values and add as we go along

    Here's what I did so far:

    Java Code:
    //Using While Loops with sentinel values to stop loops
    
    import java.util.Scanner; 
    
    public class addIntegers
    {
    	public static final int SENTINEL = 0;
    	
    	public static void main(String[] args)
    	{
    		// Variable declaration
    		int number;
    		int sum = 0;
    		
    		Scanner keyboard = new Scanner(System.in); 
    		
    		System.out.print("Enter a number to add (Press " + SENTINEL + " to end): ");
    		number = keyboard.nextInt();
    		
    		while (number != SENTINEL)
    		{
    			sum = sum + number;
    			System.out.print("Enter a number to add (Press " + SENTINEL + " to end): ");
    			number = keyboard.nextInt();
    		}
    		
    		System.out.print("\nThe sum of numbers entered before zero is " + sum + ".");
    	}
    }
    The above code has redundant code - it asks the user to input a number and grabs it in the while loop as well as above it (which was used to initialize the loop).

    I want to get rid of the redundant code. Here's my pseudo-code to what I *think* is the solution.

    Java Code:
    import java.util.Scanner; 
    
    public class addIntegers
    {	
    	public static void main(String[] args)
            {
    		// Variable declaration
    		int number;
    		int sum = 0;
    		
    		Scanner keyboard = new Scanner(System.in);
    
                // Pseudo-code begins
                  while (some condition is true)
                  {
    	              Ask user for number & inform user to press 0 to quit
    	              Get the number
    
    	              if (number is equal to zero)
    		          {
    		               print the sum of numbers entered before zero
    		          }
    	
    		          Add the number into the value of sum, which is initially zero
                  } // Repeat loop until zero is entered
            }
    }
    I am not sure what condition to come up with for the while loop. I got rid of the constant since I don't think that's necessary anymore. I have to make the while loop condition true in order to initiate the loop, and not have to use zero initially for the value of "number".

    How can I tackle this issue? I am in a beginning Java class, and we haven't hit switches yet.

    Thanks in advance for all your help.
    Last edited by Mike Miller; 09-29-2011 at 02:41 AM.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Sentinel value in a while loop

    I am not sure what condition to come up with for the while loop.
    The condition is easy! It's moreWanted or isNotFinished or some such thing.

    (1) Declare it before the while loop. And initialise it (to what?)
    (2) Make it false inside the while loop at the appropriate place (which is where? ie what makes it false?)

  3. #3
    Mike Miller is offline Member
    Join Date
    Sep 2011
    Posts
    4
    Rep Power
    0

    Default Re: Sentinel value in a while loop

    Quote Originally Posted by pbrockway2 View Post
    The condition is easy! It's moreWanted or isNotFinished or some such thing.

    (1) Declare it before the while loop. And initialise it (to what?)
    (2) Make it false inside the while loop at the appropriate place (which is where? ie what makes it false?)
    So, I could declare a "double" variable, assign it a value of say, 2.3, and pop it in the while loop. That sounds like it will work.

    That brings up my next question. Doesn't the while loop condition have to be related to the code within the while loop? In other words, what I just said above has absolutely nothing to do with the purpose of the program. Should that matter? I'm just curious.

    Thanks for the reply. It sure got me thinking about this.
    Last edited by Mike Miller; 09-29-2011 at 03:10 AM.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Sentinel value in a while loop

    Why a double variable? Your pseudo code showed a variable "some condition" which presumably should be boolean as the loop executes as long as it has the value true.

    Yes, this variable is related to the contents of the while loop. As I said before it will be set to false inside the loop when you detect that no more looping is needed.

  5. #5
    Mike Miller is offline Member
    Join Date
    Sep 2011
    Posts
    4
    Rep Power
    0

    Default Re: Sentinel value in a while loop

    Quote Originally Posted by pbrockway2 View Post
    Why a double variable? Your pseudo code showed a variable "some condition" which presumably should be boolean as the loop executes as long as it has the value true.

    Yes, this variable is related to the contents of the while loop. As I said before it will be set to false inside the loop when you detect that no more looping is needed.
    Well, the only thing I can think of doing at this point would be this:
    Java Code:
    public static void main(String[] args)
    	{
    		// Variable declaration
    		int number = 0; 
    		int sum = 0;
    		
    		Scanner keyboard = new Scanner(System.in);
    		
    		while (number != 0)
    		{ 
    			System.out.print("Enter a number to add (Press 0 to quit): ");
    			number = keyboard.nextInt();
    			
    			if (number == 0)
    			{
    				System.out.print("\nThe sum of numbers entered before zero is " + sum + ".");
    			}
    			
    			sum = sum + number; // Get sum
    		}
    	}
    Clearly the above code won't work. My while loop executes if number is not equal to zero, which requires me to give the number variable a value of zero (in order for the program to perform the addition correctly). It would hit the "if" statement within the while loop if number is given a value of zero. This is why I added a double variable as the Scanner accepts only integers, and more importantly because the double variable doesn't have anything to do directly with the program (it's just a dummy variable to execute the while loop).

    Anyway, it does work with the double variable. I'm not going to use it, but let's assume for a moment that I am. The loop continues to run after I enter zero. Is there a way to stop that? I've seen the use of break statements in such situations, although using those hasn't been recommended without prior use of switch statements.

    Thanks again.
    Last edited by Mike Miller; 09-29-2011 at 08:51 AM.

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,019
    Blog Entries
    7
    Rep Power
    20

    Default Re: Sentinel value in a while loop

    Use a for loop; it is/was normal idiom in C/C++ to do this:

    Java Code:
    for (sum= 0; (number= keyboard.nextInt()) != 0; sum+= number); // empty body
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    Mike Miller is offline Member
    Join Date
    Sep 2011
    Posts
    4
    Rep Power
    0

    Default Re: Sentinel value in a while loop

    Quote Originally Posted by JosAH View Post
    Use a for loop; it is/was normal idiom in C/C++ to do this:

    Java Code:
    for (sum= 0; (number= keyboard.nextInt()) != 0; sum+= number); // empty body
    kind regards,

    Jos
    We haven't started using for loops either. We're required to use while loops for this program.

    Thanks for your reply.

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Sentinel value in a while loop

    For future reference Jos' suggeston of using a for loop is good because the stopping condition is given "up front" at the start of the loop.

    As for using a while loop, you could try what I suggested: while(moreInput) {...

    Declare the variable as boolean before the loop
    Initialize it appropriately
    Within the loop assign it false at the appropriate place

  9. #9
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Sentinel value in a while loop

    For future reference Jos' suggeston of using a for loop is good because the stopping condition is given "up front" at the start of the loop.

    As for using a while loop, you could try what I suggested: while(moreInput) {...

    Declare the variable as boolean before the loop
    Initialize it appropriately
    Within the loop assign it false at the appropriate place

  10. #10
    RichersooN is offline Senior Member
    Join Date
    Jan 2011
    Location
    Rizal Province, Philippiines
    Posts
    167
    Rep Power
    0

    Default Re: Sentinel value in a while loop

    I think do while loop will be more appropriate for this program.

Similar Threads

  1. Counting with a sentinel loop
    By Teclis in forum New To Java
    Replies: 0
    Last Post: 03-22-2011, 07:38 PM
  2. sentinel help
    By droidus in forum New To Java
    Replies: 12
    Last Post: 03-04-2011, 02:58 PM
  3. using a "char" sentinel value for "int" input
    By jh7468 in forum New To Java
    Replies: 8
    Last Post: 03-02-2011, 11:42 PM
  4. JTextField loop 2x for-loop WEIRD!
    By Streetproject in forum AWT / Swing
    Replies: 2
    Last Post: 02-16-2011, 05:46 PM
  5. Help with Sentinel Loops
    By hedwards09 in forum New To Java
    Replies: 11
    Last Post: 11-07-2009, 07:39 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •