• Register
1 vote
170 views

Problem:

I have got an assignment from my online java class and doing the assignment and can't quite figure out what I'm doing wrong. I have to write a program that finds the sum of all squares between 1 and 100. As part of the assignment, I'm required to use a "while" statement, so no "for" statements will help. My current code is as follows below:

import java.util.Scanner;
public class SquareClass {
    public static void main(String []args ) {
        Scanner sc = new Scanner(System.in);
        int a = 1;
        int sum = 0;
        while (a <= 100) {
            a = (a*a);
            a++;
            sum = (sum + a); 
        }
        System.out.println(sum);
    }

Thanks for your positiveness and effort. I must recognise your help.

15.3k points
reopened by

Please log in or register to answer this question.

1 Answer

1 vote
 
Best answer

Solution:

You have mistaken it twice in your code. Firstly, you don't need a Scanner class. You are not gonna prompt a user. So, remove that. Secondly, if you do this in your way, you need to declare another variable to keep all the squared values added in it.

Please follow the snippet below:

int a = 1;
int squareValue;
int sum = 0;
while (a <= 100) {
    squareValue= (a*a);
    sum += squareValue; 
    a++;
}
System.out.println(sum);

 I hope you get my points. If you still have any queries, please reply to this thread, and if you get your answer leave an upvote here.

Thanks.

94.3k points
selected by