Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

taking an online self paced course and stuck

Greenhorn
Posts: 2
I just cant see how to use the user input to get the same result.
I know I need to somehow loop through the value the user enters and and increment sum .... just cant see it

Can you complete the exercise below such that it prints the sum of 1 to n numbers. The int n is taken as input from the user. Use a for loop to complete this exercise.
You will need a variable where you can store the new sum from each iteration. We have provided a variable called sum of the type int, for this purpose.

Appreciate help

Bartender
Posts: 1952
7
The best way to go about this would be to forget about reading and validating user input from a command-line for the time being. you should focus on the algorithm that calculates the sum of 1 to N integers first. Let's say you'd have to calculate the sum of all integers between 1 thru 10, how would you go about it?

Greenhorn
Posts: 2
Well. If I did it on a piece of paper,

I write down all the numbers one per line

and the results should be ..

the value of count is 1
the value of sum is 1
the value of count is 2
the value of sum is 3
the value of count is 3
the value of sum is 6
the value of count is 4
the value of sum is 10
the value of count is 5
the value of sum is 15
the value of count is 6
the value of sum is 21
the value of count is 7
the value of sum is 28
the value of count is 8
the value of sum is 36
the value of count is 9
the value of sum is 45
the value of count is 10
the value of sum is 55
55

Jelle Klap
Bartender
Posts: 1952
7
Right, now the first step to making that dynamic to support a user provided upper bound, is to replace the hard coded 10 in the termination expression of the for-loop with an int variable.
That variable has to be assigned a value somehow. You could do that interactively from the command-line as you have in your opening post: n.
Put those two together and you've got the basics finished. All that's left is validating the input - I assume the "Enter an int from 5 to 100" was part of the assignment.
So in between reading the user input, and using it in the for-loop, you should validate that it doesn't violate the lower and upper bound.

 It is sorta covered in the JavaRanch Style Guide.