TitanC
TitanC

Reputation: 139

Need a loop to repeat as many times as the user entered

I need help with this assignment. **Here is what i need the program to do:

  • Write a program that prompts a user for a number of iterations.
  • The program should then loop that many times.
  • Each loop the program should prompt the user for a number and add it to a running total.
  • Print the running total when you are done.

I cant get the program to loop as many times as the user enters. I know this is a simple fix but i cant seem to figure it out. Am i using the wrong statement for the loop?

Scanner guess = new Scanner(System.in);

int count =0;
int sum=0;
int num;

System.out.println("Enter a number");
num = guess.nextInt();

for(count =0; count <= num; count++)
{
    sum +=num;
    System.out.println("Your results are:"+sum);
}

Upvotes: 4

Views: 20381

Answers (2)

jessechk
jessechk

Reputation: 450

If you are starting at 0, then you'll want to change

for(count =0; count <= num; count++)

to

for(count =0; count < num; count++)

because it starts at 0, so that is the first iteration, and 1 is the second, etc.

Also, you need to keep asking the user every time. So you'll want to do something like this in the loop:

sum += guess.nextInt();

Lastly, you DON'T want to print the sum every time, just at the END. So AFTER the loop, print the sum.

You might have thought that having sum += num will ask the user for another number, but num is just the first number that the user entered (it won't change). You need to get the user's input every iteration.

Upvotes: 5

Floris
Floris

Reputation: 46375

You are using <= where you should be using just < in you for statement, otherwise you will go around the loop one to many times; and you should prompt for the number to add inside the loop, and include the appropriate code to keep track of the running sum there.

Something like this:

Scanner guess = new Scanner(System.in);

int count =0;
int sum=0;
int num, N;

System.out.println("How many numbers will you enter?");
N = guess.nextInt();

for(count =0; count < N; count++)
{
    System.out.println("Enter a number");
    num = guess.nextInt();
    sum +=num;
}

    System.out.println("The sum of the numbers entered is:"+sum);

Upvotes: 1

Related Questions