0

I'm having trouble with my logic and reasoning with a while loop, and returning the sum of positive numbers n, and the sum of inputs n squared. Please see my code and assist when possible, thank you.

The exercise was: /* Write a short Java method that takes an integer n and returns the sum of the squares of all positive integers less than or equal to n. * */

public class ch1dot7 
{
    public static void main (String[]args)
    {
        Scanner input = new Scanner(System.in);
    int n, m = 0, sum = 0;

    System.out.print("Please enter a value for n: ");
    n = input.nextInt();

    System.out.println("n is currently: "+n);

    if (n <= 0)
    {
        System.out.print("Please enter a value that is higher than 0   (integer)");
        n = input.nextInt();
    }

    while  (sum > n)
    {

        System.out.print("Please enter a value for m (enter a value greater     than n to exit): ");
        m = input.nextInt();

        if (m < n)
        {
            sum += m*m;
            System.out.println("sum of the squares is: " +sum); 
        }

        sum += m*m;
    }

}//end main


}//end class
ggx7
  • 49
  • 8
  • Since this is an assignment, I'm not going to give you the answer. You should take a look at your while (sum > n) condition and think through when this will / will not be true. You should also consider what code inside the while loop actually causes "e sum of the squares of all positive integers less than or equal to n" to be computed. – Lukasz P. Nov 25 '15 at 04:30

1 Answers1

0

You have misunderstood the assignment. The assignment does not ask you to take input from the user. The only input to the method is n.

The question is to make a method that takes an integer n and returns the sum of the squares of all positive integers less than n.

For example, if n is 5, you need to sum the squares of the numbers less than five which is to say the numbers 1 through 4 as follows:

(1*1) + (2*2) + (3*3) + (4*4)

1 + 4 + 9 + 16 = 30

Your method should return 30

In your while loop you are prompting the user for additional input and saving it in the variable m. This is not needed. The variable m is not needed.

Your while loop should continue while a counter variable is less than n and the counter should be incremented in each loop. Start the counter at 1 and continue to loop while that counter is less than n.

public static int sumOfSquares(int n) {
    // here you can check if n is greater than 0

    int counter = 1;
    int sum = 0;
    while (counter < n) {
        // [ sum up the square of the counter ]
        counter++;
    }

    return n;
}
Noah
  • 1,683
  • 14
  • 19