0

I'm trying to write a program that takes the output of adding two numbers in one class together and adds it to a different number. Here is the first class:

public class Add{
    public static void main(String[] args) {

        int a = 5;
        int b = 5;
        int c = a + b;
        System.out.println(c);

        }   
}

And the second:

public class AddExtra{
    public static void main(String[] args) {

    Add a = new Add();

    int b = 5;
    int c = a.value+b;

    System.out.println(c);
    }   
}

How do I get this to work? Thanks.

0

2 Answers 2

1

Suggestions:

  • You need to give the Add class a public add(...) method,
  • have this method accept an int parameter,
  • have it add a constant int to the int passed in,
  • and then have it return the sum.
  • If you want it to add two numbers, rather than a number and a constant, then give the method two int parameters, and add them together in the method.

Then create another class,

  • In this other class you can create an Add instance,
  • call the add(myInt) method,
  • and print the result returned.
Sign up to request clarification or add additional context in comments.

Comments

0

You could try

public class Add{
    public int c; // public variable

    public Add() { // This is a constructor
                   // It will run every time you type "new Add()"
        int a = 5;
        int b = 5;
        c = a + b;
    }   
}

Then, you can do this:

public class AddExtra{
    public static void main(String[] args) {
        Add a = new Add(); // Here, the constructor is run

        int b = 5;
        int c = a.c + b; // Access "a.c" because "c" is a public variable now

        System.out.println(c);
    }   
}

Read more about constructors here.

2 Comments

I hope you wouldn't actually advise making a public field. For learning purposes, maybe.
@TimS. Yes, partly, but in this case there is really no need to add a getter (or setter). In this small example it would really not be needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.