Go to Top

Saturday 1 October 2011

Input Streams in Java

Take a look at these two programs to understand the usage and syntax of these input methods in Java.

1) Using Buffered Reader : 

Java Program : 

import java.io.*;
class input_string
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String a;
     System.out.print("Enter a string : ");
     a=br.readLine();
     System.out.print("You entered : ");
     System.out.print(a+" "+a);
 }
}

2) Using Scanner : 

Java Program : 

import java.util.Scanner;
class scanner
{
 static void main()
 {
     Scanner scan=new Scanner(System.in);
     System.out.print("Enter anything : ");
     String k=scan.nextLine();
     System.out.print("\nYou have entered : "+k);
    }
}

3) Bonus : 

Special case while taking a character input : 

Java Program : 

import java.io.*;
import java.lang.*;
class input_char
{
 public void input()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     char a;
     System.out.print("Enter a character : ");
     a=(char)System.in.read();
     System.out.print("\nYou entered : "+a);
  }
}

Other than this, you can even take a String input and find out its first character using charAt(0).

For example : 

\\Rest part is omitted
String s="hello world";
char k=s.charAt(0);
System.out.print("First letter : "+k);

Output : 

First letter : h



No comments:

Post a Comment

ShareThis