Page 119 - Cs_withBlue_J_C11_Flipbook
P. 119

3.  To accept an Integer:
                   a.  Integer of size 1 byte
                      byte b = sc.nextByte();
                   b.  Integer of size 2 bytes
                      short s = sc.nextShort();
                   c.  Integer of size 4 bytes
                      int n = sc.nextInt();
                   d.  Integer of size 8 bytes
                      long l = sc.nextLong();
                 4.  To accept a real number:
                   a.  Real number of size 4 bytes
                      float f = sc.nextFloat();
                   b.  Real number of size 8 bytes
                      double d = sc.nextDouble();
                 5.  To accept a character:
                    char c = sc.next().charAt(0);
                 Let’s see an example.

                  Program 1      Write a program to input different types of values and print them.


                   1      /*Java program to read input using Scanner class */
                   2      import java.util.Scanner;
                   3      class inputoutput

                   4      {

                   5          public static void main()
                   6          {
                   7              Scanner sc = new Scanner(System.in);

                   8              char c;
                   9              byte b;

                  10              short s;
                  11              int i;

                  12              long l;
                  13              float f;

                  14              double d;
                  15              String str;

                  16              System.out.println("---------------------------------------");
                  17              System.out.print("Enter a charater : ");

                  18              c = sc.next().charAt(0);
                  19              System.out.print("Enter a number in byte: ");

                  20              b = sc.nextByte();


                                                                                                                       117
                                                                                                             Objects   117
   114   115   116   117   118   119   120   121   122   123   124