Classes and object | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Classes and object

I have created a class with two methods both with void return type and no arguments...the first method input the data and the second one has to give the desired output...but how to access variables of method one into method two...

20th Jan 2019, 12:48 PM
Utkarsh
10 Answers
0
Scope of a variable declared in a method is inside that method only. So, you can't access it in another method.
20th Jan 2019, 12:51 PM
Nikhil Sharma
Nikhil Sharma - avatar
0
I already initialized the variable as global and also it worked but the compile time is much more than expected
20th Jan 2019, 12:54 PM
Utkarsh
0
This is o9 assignments given by our clg just like those at hackerearth or codechef so I have to check for 4 test cases
20th Jan 2019, 12:54 PM
Utkarsh
0
Can you share the code??
20th Jan 2019, 12:56 PM
Nikhil Sharma
Nikhil Sharma - avatar
0
Yeah sure
20th Jan 2019, 12:56 PM
Utkarsh
0
public static class merge{ int n,m,i,j,count=0; public void getInput(){ Scanner in=new Scanner(System.in); n=in.nextInt(); int a[]=new int[n]; for(i=0;i<n;i++){ a[i]=in.nextInt(); } m=in.nextInt(); int b[]=in.nextInt(); for(i=0;i<m;i++){ b[i]=in.nextInt(); } }
20th Jan 2019, 1:04 PM
Utkarsh
0
Now I want to access all this information in a new function for merging into a new array
20th Jan 2019, 1:06 PM
Utkarsh
0
Utkarsh You are creating these arrays in getInput() method. Reference variables 'a' and 'b' will get destroyed as soon as method gets executed. So, with no reference Arrays will be cleared from memory by garbage collector. You have to declare 'a' and 'b' inside class outside the method.
20th Jan 2019, 1:22 PM
Nikhil Sharma
Nikhil Sharma - avatar
0
I already did that and i was getting my answer but then I told you ...it was showing compile time error
20th Jan 2019, 1:24 PM
Utkarsh
0
So basically there's no other way?
20th Jan 2019, 1:24 PM
Utkarsh