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?
6 Respuestas
+ 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++;
}
}
+ 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;
}
}
+ 17
@Cyrus, updated 😊
+ 5
@Shamima New update has arrived :
https://www.sololearn.com/discuss/301311/?ref=app
+ 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).
+ 1
@Shamina thanks for the help..it works as I wanted it to :)