• March 16th, 2012, 10:41 AM
Tohtekcop
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;
}
}
• March 16th, 2012, 02:28 PM
newbie