Inputting in Java

If you want to read any input in java you might be thinking how it be done. Because most people don't know how to do it. In my experience I tried many ways.But they did not solve my whole question. Finally I found a better way to read input in Java. If you are familiar with languages like C++ or C, it is quite different from the workhorse cout and cin in C++ and printf() and scanf() in C.
Now let's start the lesson,
All the input routines I'm showing here require the line

import java.io.*;

at the beginning of the source file.

Inputting a String

public static String getString() {

String s = null;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {
s = br.readLine();
} catch (Exception e) {
}
return s;
}

Before JDK 1.1.3 you cannot do this. So if you are using older version do this.

public static String getOldString() {
String s = "";
int ch;
try {
while ((ch = System.in.read()) != -1 && (char) ch != '\n') {
s += (char) ch;
}
} catch (Exception e) {
}
return s;
}

No comments:

Post a Comment