Friday, 18 January 2013

Class X-Input / Output

There are different methods of accepting data from the user.
  •  Blue J method
  •  BufferedReader
  •  Scanner
Blue J method has its own limitations.If you want to accept data from the user in between the program, forget it.

Bufferedreader:

The header file for this is import java.io.*;  You have to write this before starting the program. The problem with this method is even you accept a number, it will be considered as string.So you need to convert the string into the other data type.
Supposing you accept  10 and 20, you cannot do any arithmatic operations on them coz both are considered strings.Now, change them to int.
InputStreamReader variable1=new InputStreamReader(System.in);
BufferedReader  variable2=new BufferedReader(variable1);

The bold letters should be in caps.
InputStreamReader i=new InputStreamReader(System.in);
BufferedReader  b=new BufferedReader(i);-------------1
System.out.println("Enter name");
String n=b.readLine();---------------------------------------2
System.out.println("Enter total");
String t=b.readLine();
int tot=Integer.parseInt(t);----------------------------------3

step 1: Use the same variable (i.e) ' i'  here, which is used in the previous line.
step 2: accept the string using the variable  used in step 1.No need to convert to any other data type coz name is anyway string unless the name is 007.Even then it is not his name.
step 3: 't' is a string ,so convert to int.
similarly change string into float ,long double.Make sure you give caps wherever necessary.
 Scanner

import java.util.*; should be included in the first line.
In scanner you dont have to accept as string and convert.Directly you can accept different data types.

Scanner s=new Scanner(System.in);
System.out.println("Enter name");
String n=s.nextLine();----------------------------------1
System.out.println("Enter total");
int t=s.nextInt();----------------------------------------2

step 1 : you can use s.next() also.
step 2 : Instead of int you can accept other data types.

No comments:

Post a Comment