DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Java exercise

  1. #1
    Join Date
    Feb 2005

    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());

  2. #2
    Join Date
    Nov 2004
    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

  3. #3
    Join Date
    Feb 2005
    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
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.