Java provides a Scanner class to facilitate data input/output. In this section, you will learn about the Scanner class that is used to get input from the user. Java also defines various methods from the Scanner class that can convert user input into appropriate data types before conducting any operation on the data.
7. Echo.java
Answer:
Yes — Scanner
objects have many input methods.
Echo.java
Echo.java
import java.util.Scanner; public class Echo { public static void main (String[] args) { String inData; Scanner scan = new Scanner( System.in ); System.out.println("Enter the data:"); inData = scan.nextLine(); System.out.println("You entered:" + inData ); } } |
Here is the Java program. It reads one line of characters from the keyboard and echoes them to the monitor.
First a Scanner
object is created:
Scanner scan = new Scanner( System.in );
Then the user is prompted to type something in. Next a method of the Scanner
is called:
inData = scan.nextLine();
This reads in one line of characters and creates a String
object to contain them. A reference to this object is put into the reference variable inData
. Next the characters from that String
are sent to the monitor:
System.out.println("You entered:" + inData );
The line import java.util.Scanner;
says to use the Scanner
class from the package java.util
. Here is a run of the program on a Windows system:
Question 7:
Could the user include digits like 123 in the input characters?