# Can't get the loop to work properly

• August 8th, 2012, 09:34 PM
thegreatzo
Can't get the loop to work properly
*****Solved it myself, thanks for help*****

Hey there,
I've got a program which I need to test whether an integer n is the exact sum of k consecutive integer numbers starting from 1.
eg. 6 is 1 + 2 + 3 and therefore k = 3 and if I put in 4 then it returns false. But what I've only able to achieve so far is to get the program to add numbers 1 to n together, so if I enter 6 I get 21 because 1 + 2 + 3 + 4 + 5 + 6 = 21, but this isn't what I need the program to do. :/ I'm kinda stuck, I've tried a few other things but they aren't working.

Code :

import java.util.Scanner;
public class ExactSum {

/**
* @param args
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Type an integer:");
int n = keyboard.nextInt();

System.out.println("The number "+n+" is not an exact sum");
}
else {System.out.println("The number "+n+" is the sum of integers from 1 to "+k+" ");
}

}
}

Any help is appreciated!
• August 9th, 2012, 01:51 AM
jps
Re: Can't get the loop to work properly
My advice would be to drop the code for now. Back up and make a pseudocode. Once you get the ideas down, turning that into code is much easier.

To start you off:

You need to test whether an integer n is the exact sum of k.
So you need to get two inputs, both of which should be an integer value greater than 0.

You can break these following steps down more:
do some math..
decide what to output

Once you get each step worked out, go over the steps again and see if you can break any one step down into more than one smaller step. Like getting an integer greater than zero could involve multiple steps which might include:
-output to user what information you want
-get an integer back
-verify the integer is greater than zero

Hope that gets you back under way
• August 9th, 2012, 02:57 PM
Norm
Re: Can't get the loop to work properly
Also posted (and answered) at Need help with loop