Arguments, variables and instructions

Newbies sometimes try to do something like this function definition:

static void showDate("Today is: December 5") {
  // some code
}

Run the code does not work - it contains a syntax error. Instead of a variable, a string is written in the argument, that is, a value.

The argument must be a variable, otherwise it cannot be an argument, that is, something that takes a value when invoked.

If you need some information in the function, and you know in advance which one, then the argument is not needed for this, because we already know how to save values ​​for later use - just create a variable in the body itself:

public static void showDate() {
  var text = "Today is: December 5";
  // some code
}

Note: after defining the function (after the closing brace), we do not put ;.

The symbol ; is placed at the end of expressions. The function definition is not an expression, but an instruction. Accordingly, we cannot use it as part of other expressions and it doesn’t need ; at the end.

The concept “create function” has many synonyms: “implement”, “define” and even “implement” (from the word implement). All of them are found in everyday practice at work.

instructions

Sam makes a lot of cards, and he often needs to display repeated symbols to visualize routes. For example, as Sam illustrates the narrow roads between cities:

Meereen =-=-=-=- Myr

And so illustrates the wide trails:

Vaes Dothrak ======== Vahar

Sam somewhere found the function repeat from the class Functions. It takes two arguments: some number N and a string, and returns a string repeated N times. Here is how he uses it:

System.out.print(Functions.repeat(4));
=-=-=-=-

Sam is not very pleased. It is inconvenient to call repeat hundreds of times inside the System.out.print call.

Write for Sam the function printSeq, which itself displays the resulting repetitions. It takes two arguments, a string and a number, and prints a repeating string to the screen. To generate a string, use repeat.

Here is an example of how Sam would use the printSeq you wrote:

App.printSeq("=-", 4);
=-=-=-=-

As usual, the function needs to be public static, not just static, so that we can call it from another class.


Exercise available only for signed users.

Please sign in with your GitHub account, this is necessary to track the progress of the lessons. If you do not have an account yet, now is the time to create an account on GitHub.