Java - Using the output from one class in another - java

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.

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.

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.

Related

get the value of variable from another method

How do i print the value of variable which is defined inside another method?
This might be a dumb question but please help me out as i am just a beginner in programming
public class XVariable {
int c = 10; //instance variable
void read() {
int b = 5;
//System.out.println(b);
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println("How to print value of b here? ");
//d.read();
}
}
You can't. b is a local variable. It only exists while read is executing, and if read executes multiple times (e.g. in multiple threads, or via recursive calls) each execution of read has its own separate variable.
You might want to consider returning the value from the method, or potentially using a field instead - it depends on what your real-world use case is.
The Java tutorial section on variables has more information on the various kinds of variables.
You need to return value from your read() methods.
public class XVariable {
int c = 10; //instance variable
int read() {
int b = 5;
return b;
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println(read());
//d.read();
}
}
Return b from the read method and print it
public class XVariable {
int c = 10; //instance variable
int read() {
int b = 5;
return b;
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println(d.read());
}
}

Calling methods on objects Java

I'm taking an introduction to java programming course at university and have an exam next week. I'm going through past exam papers am sort of stuck on this question:
Consider the following class X: class X { private boolean a; private int b; ... }
(i) Write a constructor for this class. [2 marks]
(ii) Show how to create an object of this class. [2 marks]
(iii) Add a method out, which returns b if a is true, and -b otherwise. This method must be usable for any client of
this class. [2 marks]
I've included my code below, but what i'm stuck on is in the final part to this question. How does one call a method on a new object (as we haven't been taught that in class)? Or, does the question imply that the method has to be usable with any object, not just the created object?
Sorry for my awful code and dumb question, i'm really struggling with Java.
public class X {
private boolean a;
private int b;
X(final boolean i, final int j) {
a = i;
b = j;
}
static int Out(boolean a, int b) {
if (a == true) {
return b;
}
return -b;
}
public static void main(String[] args) {;
X object1 = new X(true, 5);
System.out.println(Out(object1));
}
}
You're very close to the solution. Simply make a method like this:
public int out() {
if (a) {
return b;
} else {
return -b;
}
}
Then you can call it in your main method like this:
X object1 = new X(true, 5);
System.out.println(object1.out());
NB: remove the semicolon at the end of public static void main(String[] args) {;
I think you were meant to create a non-static method named out, which can be called by the client of the class (any place where you create a new object of type X) using the dot notation
public int out() {
if(a)
return b;
else
return -b;
}
public static void main(String[] args) {
X object1 = new X(true, 5);
int result = object1.out();
System.out.println(result);
}

Inner class' instance not able to access Outer class' data member

The documentation says "An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance." This means with the instance of inner class, I can access the members of the outer class. But I am not able to do so.
public class TopLevel {
private int length;
private int breadth;
public class NonstaticNested{
private static final int var1 = 2;
public int nonStaticNestedMethod(){
System.out.println(var1);
length = 2;
breadth = 2;
return length * breadth;
}
}
public static void main(String[] args) {
TopLevel topLevel = new TopLevel();
NonstaticNested nonStaticNested = topLevel.new NonstaticNested();
// Trying to access the length variable on 'nonStaticNested' instance, but not able to do so.
}
}
I hope the comments within the main are self speaking.
public class A {
int a = 1;
public static void main(String[] args) {
B b = new B();
// Works as "a" is defined in "A"
System.out.println(b.a);
// Works as "b" is defined in "B"
System.out.println(b.b);
C c = new C();
C.D d = c.new D();
// Works as "c" is defined in "c"
System.out.println(c.c);
// Works as "d" is defined in "D"
System.out.println(d.d);
// Error here as there is no "c" defined within "D", it´s part of "C" and here´s your
// logical mistake mixing it somewhat with what inheritance provides (just my guess).
System.out.println(d.c);
}
}
class B extends A {
int b = 1;
}
class C {
int c = 1;
class D {
int d = 2;
public D() {
// Has access to "c" defined in C, but is not the owner.
c = 2;
}
}
}

Why am I getting a "; expected" error?

public class homework
{
public static void intPow(int a, int b)
{
Math.pow(a,b);
}
public static void main(String args[])
{
intPow();
}
}
I'm trying to learn how to create a method, but I keep getting 10 ; expected errors. I know this code isn't correct, but I can't seem to find how to create a method correctly. In this case I'm trying to create a method that returns a^b.
You need to pass two int parameters into intPow():
public static void main(String args[])
{
int a = 2;
int b = 5;
intPow(a, b); //32
}
Furthermore, you should probably return an int from intPow() so you can play with it later:
public static int intPow(int a, int b) {
return Math.pow(a, b);
}
Then in main():
public static void main(String args[])
{
int a = 2;
int b = 5;
int power = intPow(a, b); //32
System.out.println(power);
}
pass two int values in intPow();
intPow(5,5);
And anyways the value would not be printed.
You need to use System.out.println() to print it.
Change
intPow();
to
intPow(2,3); // or any number
You declare intPow as a function that takes two parameters. But when you call it from main, you dont pass any. To fix this, change this line in main -
intPow();
to
intPow(1, 2);//or whatever other numbers you want.
public class homework
{
public static int intPow(int a, int b)
{
return Math.pow(a,b);
}
public static void main(String args[])
{
int a = 3;
int b = 4;
int result = intPow(a, b);
System.out.println(result);
}
}
If the goal is to create a method that returns a^b, the method should return a value. You probly need to convert to int though, because Math.pow works with doubles.
public static int intPow(int a, int b) {
return (int) Math.pow(a,b);
}
then call it using two parameters for a and b:
int result = intPow( 2, 3 );

swap two numbers using call by reference

Can we swap two numbers in Java using pass by reference or call by reference?
Recently when I came across swapping two numbers in Java I wrote
class Swap{
int a,b;
void getNos(){
System.out.println("input nos");
a = scan.nextInt();
b = scan.nextInt(); // where scan is object of scanner class
}
void swap(){
int temp;
temp = this.a;
this.a = thisb;
this.b = this.a;
}
}
In the main method I call the above mentioned methods and take two integers a,b and then using the second method I swap the two numbers, but relative to the object itself....
Does this program or logic come under pass by reference?
And is this correct solution?
Yes and no. Java never passes by reference, and your way is one workaround. But yet you create a class just to swap two integers. Instead, you can create an int wrapper and use pass it, this way the integer may be separated when not needed:
public class IntWrapper {
public int value;
}
// Somewhere else
public void swap(IntWrapper a, IntWrapper b) {
int temp = a.value;
a.value = b.value;
b.value = temp;
}
As the comments show, I might not have been clear enough, so let me elaborate a little bit.
What does passing by reference mean? It means that when you pass an argument to the method, you can change the original argument itself inside this method.
For example, if Java was pass-by-reference, the following code will print out x = 1:
public class Example {
private static void bar(int y) {
y = 10;
}
public static void main(String[] args) {
int x = 1;
bar(x);
System.out.println("x = " + x);
}
}
But as we know, it prints 0, since the argument passed to the bar method is a copy of the original x, and any assignment to it will not affect x.
The same goes with the following C program:
static void bar(int y) {
y = 1;
}
int main(int argc, char * argc[]) {
int x = 0;
bar(x);
printf("x = %d\n", x);
}
If we want to change the value of x, we will have to pass its reference (address), as in the following example, but even in this case, we will not pass the actual reference, but a copy of the reference, and by dereferencing it we will be able to modify the actual value of x. Yet, direct assignment to the reference will no change the reference itself, as it is passed by value:
static void bar(int &y) {
*y = 1;
y = NULL;
}
int main(int argc, char * argc[]) {
int x = 0;
int * px = &x;
bar(px);
printf("x = %d\n", x); // now it will print 1
printf("px = %p\n", px); // this will still print the original address of x, not 0
}
So passing the address of the variable instead of the variable itself solves the problem in C. But in Java, since we don't have addresses, we need to wrap the variable when we want to assign to it. In case of only modifying the object, we don't have that problem, but again, if we want to assign to it, we have to wrap it, as in the first example. This apply not only for primitive, but also for objects, including those wrapper objects I've just mentioned. I will show it in one (longer) example:
public class Wrapper {
int value;
private static changeValue(Wrapper w) {
w.value = 1;
}
private static assignWrapper(Wrapper w) {
w = new Wrapper();
w.value = 2;
}
public static void main(String[] args) {
Wrapper wrapper = new Wrapper();
wrapper.value = 0;
changeValue(wrapper);
System.out.println("wrapper.value = " + wrapper.value);
// will print wrapper.value = 1
assignWrapper(w);
System.out.println("wrapper.value = " + wrapper.value);
// will still print wrapper.value = 1
}
}
Well, that's it, I hope I made it clear (and didn't make too much mistakes)
import java.util.*;
public class Main
{
int a,b;
void swap(Main ob)
{
int tmp=ob.a;
ob.a=ob.b;
ob.b=tmp;
}
void get()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a and b: ");
a=sc.nextInt();
b=sc.nextInt();
}
public static void main(String[] args) {
Main ob=new Main();
ob.get();
ob.swap(ob);
System.out.println(ob.a+" "+ob.b);
}}

Categories