How can I declare a method with a new variable, which I then can use in my main? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can I declare a method with a new variable, which I then can use in my main?

I want to declare a method which brings a new variable into my code (and also prints something but that's not relevant), I then want to be able to call the method in my main and use the previously declared variable in combination with other variables I declared in my main. How is that doable?

7th Apr 2017, 4:52 PM
Xaver
6 Answers
+ 18
I guess you're referring to global static variable. If the following program doesn't help, can you give any example like what kind of program you're trying to implement? I'd be glad to guess again :) public class Program { static int counter = 0; public static void main(String[] args) { increment(); System.out.println(counter); // 1 increment(); System.out.println(counter); // 2 for(int i=0; i<counter; i++){ // do something } } public static void increment(){ System.out.println("Irrelevant stuffs go here..."); counter++; } }
7th Apr 2017, 5:48 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 17
Just return the new variable from the method. public class Program { public static void main(String[] args) { int x=3, y=7; int result = x+y+newValue(); // 3+7+5 System.out.println(result); // 15 } public static int newValue(){ System.out.println("Irrelevant stuffs go here..."); int a = 5; return a; } }
7th Apr 2017, 5:05 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 17
@Cyrus, updated 😊
7th Apr 2017, 6:09 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 5
@Shamima New update has arrived : https://www.sololearn.com/discuss/301311/?ref=app
7th Apr 2017, 5:58 PM
Cyrus Ornob Corraya
Cyrus Ornob Corraya - avatar
+ 1
Thank you for the quick answer but I think I might have explained myself a bit wrong. The main purpose of my method is to print something and the variable I want to declare in this method should act as a counter of some sort (which I also want to use for other things as well in my main).
7th Apr 2017, 5:26 PM
Xaver
+ 1
@Shamina thanks for the help..it works as I wanted it to :)
8th Apr 2017, 7:00 AM
Xaver