In this Java program, we will learn about taking an integer, character, float and string input from user using Scanner class and then printing integer, character, float and string on screen using System.out.format method.
To perform any input operation using Scanner in a java program, we have to first import Scanner class as :
import java.util.Scanner;
While creating an object of Scanner class, we initialize it with predefined standard input stream System.in as
Scanner scanner = new Scanner(System.in);
Reading Integer using Scanner
To read integers, we use nextInt() method, which parses the next input token as an integer value and return it.
For Example,int v_int; v_int = scanner.nextInt();
Reading Character using Scanner
To read a character, we use next() method followed by charAt(0). next method returns the next input token as string as the charAt(0) returns the first character of token.
For Example,char c; c = scanner.next().charAt(0);
Reading String using Scanner
For reading a string, we use nextLine() method which returns a string till end of the line(newline character).
For Example,String str; str = scanner.nextLine();
Reading Float using Scanner
To read integers, we use nextFloat() method, which parses the next input token as an float value and return it.
For Example,float v_float; v_float = scanner.nextFloat();
Java Program for Taking input from user using Scanner
package com.tcc.java.programs; import java.util.Scanner; public class TakingInput { public static void main(String[] args) { char c; int v_int; float v_float; String str; Scanner scanner; scanner = new Scanner(System.in); // Taking input from user System.out.println("Enter a String"); str = scanner.nextLine(); System.out.println("Enter a Character"); c = scanner.next().charAt(0); System.out.println("Enter an Integer"); v_int = scanner.nextInt(); System.out.println("Enter a Float"); v_float = scanner.nextFloat(); // Printing data entered by user System.out.println("You Entered Following Data:"); System.out.format("Char : %c\n", c); System.out.format("Integer : %d\n", v_int); System.out.format("Float : %f\n", v_float); System.out.format("String : %s", str); } }Output
Enter a Character A Enter an Integer 123 Enter a Float 1234.6 You Entered Following Data: Char : A Integer : 123 Float : 1234.599976 String : TectCrashCourse
Recommended Posts