Has Java's default output function already accepted several parameters?

11

My teacher taught the class how to use System.out.println("Mensagem") in this way for the class (the type of total_alunos does not matter):

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

After popping some errors on the computers I said that it was necessary to concatenate the string through + , which worked, but she said that commas should work as well. At some point, was it possible to perform this function in the way presented above? If so, which version of Java?

    
asked by anonymous 22.06.2015 / 20:34

3 answers

8

Maybe your teacher is confusing println() with 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.");
    }
}

Result:

  

There are 10 students in the class.

According to % "%" accepts a variable amount of parameters and its signature is as follows:

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

PS: Pay attention to printf() and %d within the first pair of double quotation marks that are the format specifiers of the other arguments, different from how you are in your question code that does not have them.

Since %s does not accept several parameters and there is no way to pass several arguments to it, not by concatenating them and transforming them into only one, however, there is no way to concatenate with a comma and there never was.

    
22.06.2015 / 20:38
4

If you look at Method println(String) of type PrintStream , it does not accept as arguments String , Qualquertipo , String , thus the need to concatenate using + .

This is also valid if you try to pass Object .

Example Below:

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

Link to Reference in Java Doc

    
22.06.2015 / 20:43
0

Try replacing the code:

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

by

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

The output will be:

  

There are 5 students in the class.

    
22.05.2017 / 21:35