Reputation: 11
My code is not working for this method, I am trying to add up the sum of the sum of the numbers; if n = 3, return 10; n =6, return 56;
this is my code:
public int sumOfSums(int n) {
int[] numArray = new int[n];
int totalSum = 0;
int counter = 0;
for (int i = 0; i < n ; i++){
numArray[i] = n;
n--;
System.out.println(numArray[i]);
}
for (int j = 0; j < n; j++){
totalSum += numArray[j];
System.out.println("I am in for loop");
if (j == n-1){
j = 0;
counter++;
}
if (counter == n){
return totalSum;
}
}
return totalSum;
}
Also total sum is not being assigned, this is the error I get:
----jGRASP exec: java -ea HazMath
-37337 is not prime
1
Exception in thread "main" java.lang.AssertionError
at HazMath.main(HazMath.java:133)
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
from running this assert:
public static void main(String[] args){
HazMath HM=new HazMath();
assert !HM.isPrime(3);
assert !HM.isPrime(-37337);
assert HM.sumOfSums(1) == 1;
assert HM.sumOfSums(3) == 10;
assert HM.sumOfSums(6) == 56;
assert HM.sumOfSums(25) == 2925;
assert HM.sumOfSums(-5) == 0;
System.out.println("All tests passed. VICTORY!");
}
Upvotes: 1
Views: 62
Reputation: 2208
You are asserting on Prime which threw AssertionError. In case you intend to continue with the remaining tests, you will need to catch the Error.
Example code:
try {
assertTrue(hm.isPrime(-37337));
}
catch (AssertionError e ) {
e.printStackTrace();
}
Further, if you are worried about your code not entering the second loop, then it is because of the following:
In the first loop, you are decrementing the value of n to 0.
And then you are comparing if 0 is less than 0 in the second loop.
Upvotes: 1
Reputation: 7232
Not a direct answer to your question, but you can calculate the sum of sums more directly and avoid your loops by using the formula:
f(n) = n(n+1)(n+2) / 6
Rewriting your code to use this function will likely fix your issue in the process.
Upvotes: 1