# Help with Java please



## Akumos (Sep 25, 2009)

Hi can someone help me out... If I don't give the variable result a value, it throws an error saying "it may never initialize", If I do, it seems to ignore my add() method.

Don't know about getters and setters yet, so trying not to use them. Thanks for any input, I appreciate it.

code:


```
import javax.swing.JOptionPane;

public class load {

	public static void main(String[] args) {
		
		int a, result;
		String b;
		
		b = JOptionPane.showInputDialog("Enter a number to continue:\n\n1. Add\n2. Subract\n");		
		a = Integer.parseInt(b);
		
		if (a == 1)
		{			
			add(result);		
			JOptionPane.showMessageDialog(null, "Result is " +result+".");
			
		}		
		else
		{			
			JOptionPane.showMessageDialog(null, "Result is " +result+".");
		}
	}
		
	public static int add(int result) {
	
		int a, b;
		String c, d;
	
		c = JOptionPane.showInputDialog("Enter first number to add");
		a = Integer.parseInt(c);
	
		d = JOptionPane.showInputDialog("Enter second number to add");
		b = Integer.parseInt(d);
	
		result = a + b;
	
		return result;
	
	}
}
```


----------



## Yukikaze (Sep 25, 2009)

Try this as a quick fix. I hope I haven't missed anything since I just compiled it with the Mk1 eyeball.

You didn't use the returned value from the add() method, so there was little wonder that the value was ignored. The fact you did:

result = a + b;

inside the method is not enough to guarantee that the external value will be modified because you are using a primitive (which is passed by value, that is copied) and not an object (which is passed by reference, that is, what is copied is the address of the value, rather than the value itself - If you would have passed an object, modifying it inside the method would have changed its value everywhere).

Hope this helps (and works).


```
import javax.swing.JOptionPane;

public class load {

	public static void main(String[] args) {
		
		int a, result;
		String b;
		
		b = JOptionPane.showInputDialog("Enter a number to continue:\n\n1. Add\n2. Subract\n");		
		a = Integer.parseInt(b);
		
		if (a == 1)
		{			
			result = add();		
			JOptionPane.showMessageDialog(null, "Result is " +result+".");
			
		}		
		else
		{			
			JOptionPane.showMessageDialog(null, "Result is " +result+".");
		}
	}
		
	public static int add() {
	
		int a, b;
                int result;
		String c, d;
	
		c = JOptionPane.showInputDialog("Enter first number to add");
		a = Integer.parseInt(c);
	
		d = JOptionPane.showInputDialog("Enter second number to add");
		b = Integer.parseInt(d);
	
		result = a + b;
	
		return result;
	
	}
}
```


----------



## Akumos (Sep 26, 2009)

result = add();

Worked great!!

Thanks Yukikaze for replying, I know answering programming qustions can be long winded but I appreciate it!


----------

