• Status: Solved
• Priority: Medium
• Security: Public
• Views: 638

# query-controlled” loop

I am trying to Write a “query-controlled” loop that will continue to input int values from the user, adding each to the int value sum, and then ask if the user has another value to input, until the user says that there are no more values.  Assume that the scanner class has been imported.

Do you think this is right

int total =0,val=0;
do
{
scanner sc = new scanner();
System.out.println(“Enter a value (enter 0 to quit) :”);
val = sc.intValue();
total+=val;

}
while(val!=0)
0
Ansary100
• 2
1 Solution

Commented:
Ansary100,

I'm afraid I'm not a Java expert, but one little thing does jump out at me: you do not seem to output anything.  The user might want to know the final value of sum (total).

mathbiol
0

Author Commented:
Why you are imagining that I’m a student I’m NOT A STUDENT IN ANY PLACE. I’m a self learner. Please stop saying I’m a student.. I’m maybe a student of you and the others because I’m trying to learn from you and the others
0

Commented:
You should only initialise the class scanner once before the loop

int total =0,val=0;
scanner sc = new scanner();

do
{
System.out.println(“Enter a value (enter 0 to quit) :”);
val = sc.intValue();
total+=val;
}
while(val!=0)

System.out.println(“Your total is ” + total);
0

Commented:
Ansary,

I admire people who can do self-learning.

I think you've chosen a good way to work with the Exchange when you post your own code and ask for feedback.  I think a learner doesn't learn as much when he posts a problem definition and then an expert posts a fully-coded program in response.

I am guessing that you are working with one or two books that show some examples and then provide some exercises for the learner to do on his own.  That is a great way to learn to program.  I hope that you are trying to compile and run your programs.  Debugging is a fundamental skill that will stand you in good stead.

When you post your questions, it might be helpful to know what book, if any, the exercise was taken from.

You might also want to do a little housekeeping every few days and close out as many of your open questions as possible.

mathbiol
0

## Featured Post

• 2
Tackle projects and never again get stuck behind a technical roadblock.