Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

Hi I am trying to call a method to compute 1 - 3 + 5 - 7 + .. .. - (n - 2) + n
For example: n = 9 the Series would look like 1 - 3 + 5 - 7 + 9 = 5

I am not looking to get spoon fed. Just hoping someone could help me understand the logic and let me know if I am even close.

Here is what I have so far.

import javax.swing.JOptionPane;

public class OddSum {

public static void main(String[] args) {

int oddSeries, m, n;
String num1Str, num2Str;

// Get a pair of positive Integers from users
num1Str = JOptionPane.showInputDialog("Enter a positive integer:");
m = Integer.parseInt(num1Str);
num2Str = JOptionPane.showInputDialog("Enter a positive integer:");
n = Integer.parseInt(num2Str);

// Call a method to compute 1 - 3 + 5 - 7 + .. .. - (n - 2) + n

oddSeries = myOddNum(n);

// output the result
System.out.println("(OddNum) The series of 1 to " + n + " = " + oddSeries);
}

// Method myOddNum with on Parameter
public static int myOddNum(int myN) {

int localSum, oddnum;

localSum = 0;
oddnum = 0;
for (int i = 1; i <= myN; i++) {
if (i%2 != 0);{
oddnum = myN - 2;}
localSum = localSum + oddnum;}
return localSum;
}
}