Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
How to give the value of a methods variable to Global in java?
Suppose this is a program.
import java.util.Scanner;
Class A {
int a1;
public void VAS ()
{
Scanner src=new Scanner(System.in);
int a1;
a1=src.nextInt();
}
}
Class B {
int b1;
public void VBS ()
{
Scanner src=new Scanner(System.in);
int b1;
b1=src.nextInt();
}
}
class C {
public void VCS
{
int c1;
VAS g= new VAS();
VBS h=new VBS();
c1=(g.a1 + h.b1);
System.out.println(c1);
}
}
class D
{
public static void main (String args[])
C c= new C();
c.VCS();
}
Now my problem is i want to add both the integers a1 and b1 in Class C's c1 variable.
But i don't want to call the whole methods i.e VAS and VBS. Just the variables.
I know that the values of variables inside a method cannot be accessed outside the class. Thats why i want to give there values to global variable and call the global variable.
I tried the program it shows "NullPointerException"
This is like a short e.g. of that program the original program has lot more variables and other things, soo i cant call the whole methods VBS and VAS. I just want to use the variable in those 2 methods too add them in C class.
2 Answers
- JordanLv 58 years ago
First of all a quick reminder of naming convention. Classes begin with a capital letter, methods with a lowercase. This makes everything much easier to read.
You have two options here, you are asking for the variables to be global (public), which they already are by default since you didnt declare what they should be. In order to access them you need to create an object using the class and use the object to access the variable which you attempted to do here:
VAS g= new VAS();
VBS h=new VBS();
This should read:
A g = new A();
and B h = new B();
Then:
g.a1 and h.b1 should work.
However this is a terrible way to use this program, using private variables and getters/setters ensure encapsulation and is a much better option.
- KaydellLv 78 years ago
I made some changes to your code. One thing that I think that you need to understand is that your code has two variables called a1 and two variables called b1. What I did is I removed the definition of the local variables a1 and b1 so that the variables a1 and b1 that are defined as instance variables would be used instead.
Here's the fixed code: