-
Java exercise
I am currently studying java and want to brush up on my skills. I have written this program shown below where a user enters 2 integers via a JOptionPane and then prints the sum, the product and average of the two integers. The 2 integers seem not to be going into the methods can someone please tell me what im doing wrong. Thanks.
import javax.swing.*;
/*
* Created on Dec 20, 2004
*
*/
/**
* @author Trixma
* @version 1.0
*/
public class Exercise4 {
private int input1;
private int input2;
public Exercise4(){
String numberOne = JOptionPane.showInputDialog("Enter an Integer");
String numberTwo = JOptionPane.showInputDialog("Enter an Integer");
int input1 = Integer.parseInt(numberOne);
int input2 = Integer.parseInt(numberTwo);
}
public int sum(){
int sum = input1 + input2;
return sum;
}
public int product(){
int product = input1 * input2;
return product;
}
public int average(){
int average = (input1 + input2)/ 2;
return average;
}
public static void main(String[] args) {
Exercise4 myTwoDigits = new Exercise4();
System.out.println("The sum of the two integers entered is: " + myTwoDigits.sum());
System.out.println("The product of the two integers entered is: " + myTwoDigits.product());
System.out.println("The average of the two integers entered is: " + myTwoDigits.average());
}
}
-
You retrieve the input values like this inside the constructor:
int input1 = Integer.parseInt(numberOne);
int input2 = Integer.parseInt(numberTwo);
but then you also redeclare the two variables input1 and 2 as local values inside the constuctor method.
the variables returned by the other methods refer to the class-global variables input1 and 2.
do this:
input1 = Integer.parseInt(numberOne);
input2 = Integer.parseInt(numberTwo);
mkay ?
eschew obfuscation
-
Thanks. Ive fixed the problem
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks