Results 1 to 2 of 2
- 01-12-2012, 06:07 AM #1
Member
- Join Date
- Jan 2012
- Posts
- 24
- Rep Power
- 0
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(); } } }
-
Re: Having trouble with programming exercise, help?
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
-
Programming exercise for beginners
By FOX427 in forum New To JavaReplies: 5Last Post: 07-16-2011, 07:43 AM -
Programming Project trouble..
By hockey9999 in forum New To JavaReplies: 1Last Post: 12-20-2010, 08:07 PM -
Need help with a programming exercise
By ararar in forum New To JavaReplies: 9Last Post: 11-19-2010, 05:57 AM -
Have I done this exercise right?
By ccie007 in forum New To JavaReplies: 7Last Post: 09-28-2010, 05:54 PM -
help with exercise
By e_as're in forum New To JavaReplies: 3Last Post: 09-25-2007, 10:14 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks