Has the standard Java output function accepted several parameters?

Asked

Viewed 191 times

11

My teacher taught the class to use the System.out.println("Mensagem") this way for the class (the type of total_alunos it doesn’t matter):

System.out.println("Existem ", total_alunos, " alunos na classe.");

After popping a few errors in the computers I said that it was necessary to concatenate the string through the +, which worked, but she said the comma should work, too. At some point, was it possible to execute this function in the above manner? If yes, in which version of Java?

3 answers

9


Maybe your teacher is confusing the println() with the printf(), because something similar to what you want can be done like this:

public class Teste {
    public static void main(String[] args) {
        int totalAlunos = 10;
        System.out.printf("Existem %d %s", totalAlunos, " alunos na classe.");
    }
}

Upshot:

There are 10 students in the class.

According to the documentation the printf() accepts a variable amount of parameters and its signature is as follows:

public PrintStream printf(String format, Object... args)

PS: Pay attention to %d and %s within the first pair of double quotes that are the format specifiers of the other arguments, different from how it is in the code of your question that does not have them.

Already the println() does not accept several parameters and there is no way to pass several arguments to it except by concatenating them and transforming into only one, however, there is no way to concatenate with comma and there has never been.

  • 1

    That’s exactly what happened @Math, thank you.

4

If you observe the Method println(String) of the kind PrintStream, not accepted as arguments String , Qualquertipo ,String, thus the need to concatenate using +.

This is also valid if you try to pass one Object.

Example Below :

 System.out.println("Linked account: "+  client.getAccountInfo().displayName + " account: ");

Reference link in Java Doc

  • If you would like to add the link: http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#out

  • I will edit my reply @Math

0

Try to replace the code:

System.out.println("Existem ", total_alunos, " alunos na classe.");

for

System.out.println("Existem "+ total_alunos + " alunos na classe.");

the exit will be:

There are 5 students in the class.

  • 1

    You read his question?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.