Results 1 to 2 of 2
  1. #1
    atac57 is offline Member
    Join Date
    Jan 2012
    Posts
    24
    Rep Power
    0

    Default Having trouble with programming exercise, help?

    Write a program that adds up integers that the user enters. First the programs asks how many numbers will be added up. Then the program prompts the user for each number. Finally it prints the sum.

    How many integers will be added:
    5
    Enter an integer:
    3
    Enter an integer:
    4
    Enter an integer:
    -4
    Enter an integer:
    -3
    Enter an integer:
    7

    The sum is 7

    Be careful not to add the number of integers (in the example, 5) into the sum.


    I know you have to use a while loop in this case, but I can't figure out how to make the while loop loop as many times as what you enter for the "num" variable. Any help? Thanks.

    Java Code:
    import java.util.Scanner;
    
    class Simulation{
    	public static void main (String args[]){
    		Scanner scan = new Scanner(System.in);
    		int num;
    		
    		System.out.println("How many integers will be added:");
    		num = scan.nextInt();
    		
    		while (num ???)
    		{
    			System.out.println("Enter an integer: ");
    			num = scan.nextInt();
    			
    		}		
    	}
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Having trouble with programming exercise, help?

    Quote Originally Posted by atac57 View Post
    I know you have to use a while loop in this case, but I can't figure out how to make the while loop loop as many times as what you enter for the "num" variable. Any help? Thanks.
    I would approach this differently and would not use the assumptions you are using. My rule of thumb is this: if you will know before the loop starts how many times the loop will loop, use a for loop. If you don't know how many times it will loop (for instance if it will loop until the user types in a sentinel phrase or number), then use a while loop. In your example above you in fact do know how many times the loop will occur before the loop starts.

Similar Threads

  1. Programming exercise for beginners
    By FOX427 in forum New To Java
    Replies: 5
    Last Post: 07-16-2011, 07:43 AM
  2. Programming Project trouble..
    By hockey9999 in forum New To Java
    Replies: 1
    Last Post: 12-20-2010, 08:07 PM
  3. Need help with a programming exercise
    By ararar in forum New To Java
    Replies: 9
    Last Post: 11-19-2010, 05:57 AM
  4. Have I done this exercise right?
    By ccie007 in forum New To Java
    Replies: 7
    Last Post: 09-28-2010, 05:54 PM
  5. help with exercise
    By e_as're in forum New To Java
    Replies: 3
    Last Post: 09-25-2007, 10:14 AM

Posting Permissions

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