Input and output
Getting input from the user
In Java, you can use the Scanner
class to get input from the user. Here's an example:
In the above example, we use the Scanner
class to get input from the user. We first create a new Scanner
object and pass in System.in
to indicate that we want to get input from the standard input stream (i.e. the user).
We then use the nextLine()
method to get a string input from the user, and the nextInt()
method to get an integer input from the user. We store the input in the name
and age
variables, respectively.
Displaying output to the user
In Java, you can use the System.out.println()
method to display output to the user. Here's an example:
In the above example, we use the System.out.println()
method to display output to the user. We pass in a string that contains the message we want to display, as well as the variables name
and age
.
Using formatted output
In Java, you can use the System.out.printf()
method to display formatted output to the user. Here's an example:
In the above example, we use the System.out.printf()
method to display formatted output to the user. We pass in a format string that contains placeholders for the variables name
and age
. The %s
placeholder is used for strings, and the %d
placeholder is used for integers. We then pass in the values of name
and age
as additional arguments to the method. The character is used to add a newline after the message.
Last updated