I
I
Ivan Ivanov2017-09-20 00:22:42
Java
Ivan Ivanov, 2017-09-20 00:22:42

How do functions work in JAVA?

Hello dear, below I will give the JavaScript code, please explain how to do the same in JAVA.

JavaScript

var text = "Hello World";
function run(){
for(var i=0;i<10;i++) {
document.write(text);
}
}
run();

I made some JAVA sketches, but apparently I'm confusing something with the syntax
JAVA

class Rextester
{
public static void main(String[] args) {
String text = "JavaRush. Learn once — use anywhere";
run();
}
public static void run() {
for(int i = 0; i<10; i++ ){
System.out.println(text);
}
}
}

Or in JAVA, a function must always take some kind of argument?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2017-09-20
@ZZiliST

And if you really want to have a "global" text variable:

class Rextester {
    public static String text;

    public static void main(String[] args) {
        text = "JavaRush. Learn once — use anywhere";
        run();
    }

    public static void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(text);
        }
    }
}

H
hudrogen, 2017-09-21
@hudrogen

The text variable is in the scope of the main method, the run method does not see it. The run method will start seeing String text if you move the String text into the scope of the class - as a class field. And since this field is accessed from a static method, this variable must be static, or access it by creating an instance of the Rextester class

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question