Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

#### ElementOfMagic

Hello.

I was wondering whether anybody could possibly tell me why, the below Java program doesn't output anything to the screen when I run it.
It's supposed to print the sum of square numbers between 1 and 10. It compiles without a problem, but for some reason when I try to execute it, it just jumps straight to the end of the program and I have no idea why?

Code:
``````import java.util.*;

public class SquareProgram {
public static void main(String args[])
{

int n = 10;
int square = n*n;

square(0);

sumOfSquares(0);

}

public static int square(int n)

{
int square = n*n;

return n*n;

}

public static int sumOfSquares(int n)

{
int sum = 0;
int square = n*n;
int i;
for (i = 1; i <= n; i++)
{
sum = sum + square;

System.out.println("The sum of squares between 1 and "+n+" is "+sum+"");
}
return sum;

}
}``````
Any help/assistance would be greatly appreciated.

#### Ent

Josiah
For starters, you need the square line inside the for loop.
Secondly, you want to be squaring i, not n.
i.e. you want 1 squared plus 2 squared plus 3 squared.
not 3 squared plus 3 squared plus 3 squared.

Also, what do you mean by it jumps to the end? Does it exit before you can see anything?

#### ElementOfMagic

For starters, you need the square line inside the for loop.
Secondly, you want to be squaring i, not n.
i.e. you want 1 squared plus 2 squared plus 3 squared.
not 3 squared plus 3 squared plus 3 squared.

Also, what do you mean by it jumps to the end? Does it exit before you can see anything?
Thanks, but that doesn't make a difference.
And yes, that's what jumps to the end means.

#### Ent

Josiah
Try putting in an extra command at the end (input commands work well) to force it to delay.

#### andythepandy

First of all your program isn't printing anything because you are calling the function sumOfSquares with an argument of 0, which will mean the function never goes into the for loop - where the system.out.println is.

Also, as Ent said, there is a problem with your code that calculates the sum
Try this:
Code:
``````public static int sumOfSquares(int n) {
int sum = 0;
int square;
int i;
for (i = 1; i <= n; i++) {
square = i*i;
sum = sum + square;
}
System.out.println("The sum of squares between 1 and "+n+" is "+sum+"");
return sum;
}``````

Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

As Seen On