Monday, June 26, 2017

MyScanner Class

Tags

Following Code will define a class MyScanner to take input from user using InputStreamReader ..

Code:


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

class MyScanner {
InputStreamReader i;
BufferedReader br;
public MyScanner(InputStream x) {
i=new InputStreamReader(x);
br=new BufferedReader(i);
}
public int nextInt() {
int a=0;
try {
a =Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("Error:"+e);
}
return a;
}
public float nextFloat() {
float a=0;
try {
a =Float.parseFloat(br.readLine());
} catch (Exception e) {
System.out.println("Error:"+e);
}
return a;
}
public double nextDouble() {
double a=0;
try {
a =Double.parseDouble(br.readLine());
} catch (Exception e) {
System.out.println("Error:"+e);
}
return a;
}
public long nextLong() {
long a=0;
try {
a =Long.parseLong(br.readLine());
} catch (Exception e) {
System.out.println("Error:"+e);
}
return a;
}
public String nextLine() {
String a=null;
try {
a =br.readLine();
} catch (Exception e) {
System.out.println("Error:"+e);
}
return a;
}
public String next() {
String a="";
int ch=0;
try {
while(true) {
ch=br.read();
if(ch==32 || ch==10){
break;
}
a=a.concat(""+(char)ch);
}

} catch (Exception e) {
System.out.println("Error:"+e);
}
return a;
}

/*class MyScanner1 extends Scanner {
// error because Scanner is final class
}*/

}
public class MyScannerDemo {
public static void main(String[] nt) {
MyScanner in=new MyScanner(System.in);
//Character
char ch=in.next().charAt(0);
System.out.println("Entered Character: "+ch);
//Integer
int i=in.nextInt();
System.out.println("Entered Integer: "+i);


}
}

Output: