It is very easy process to read user input from the console using Scanner class. You have to just create one object of scanner class to accept user input from the user. It is very simple program. I have written very simple program for you. Just try to understand it.
Code:
import java.io.*;
import java.util.*;
public class ScanConsoleEg
{
public static void main (String arg[]) {
Scanner scanners1 = new Scanner (System.in);
try {
System.out.printf ("Input int (e.g. %5d): ",6794);
int int_vals = scanners1.nextInt ();
System.out.println (" You have entered " + int_vals +"\n");
System.out.printf ("Input float (e.g. %3.2f): ", 6.35);
float float_vals = scanners1.nextFloat ();
System.out.println (" You have entered " + float_vals +"\n");
System.out.printf ("Input double (e.g. %6.2e): ",1.2568);
double double_vals = scanners1.nextDouble ();
System.out.println (" You entered " + double_vals +"\n");
}
catch (InputMismatchException es) {
System.out.println ("Mismatch exception:" + es );
}
}
}
Bookmarks