Noi a scuola ne usiamo un'altra, ConsoleMia.
I prof l'hanno trovata da qualche parte in rete, io la metto si sa mai che a qualcuno interessi.
codice:
// ConsoleMia.java
import java.io.InputStream;
import java.io.InputStreamReader;
/** An easy interface to read numbers and strings from standard input.
@version 1.10 10 Mar 1997
@author Cay Horstmann
@see InputStreamReader */
public class ConsoleMia extends InputStreamReader {
/** Costruttore base.
@param in Stream di input.
*/
public ConsoleMia(InputStream in) {
super(in);
} // ConsoleMia
/** Print a prompt on the ConsoleMia but don't print a newline.
@param prompt The prompt string to display.
*/
private static void printPrompt(String prompt) {
System.out.print(prompt);
System.out.flush();
} // printPrompt
/** Read a string from the ConsoleMia. The string is terminated by a newline.
@return The input string (without the newline).
*/
public static String readLine() {
int ch;
String r = "";
boolean done = false;
while (!done)
try {
ch = System.in.read();
if (ch < 0 || (char)ch == '\n')
done = true;
else if ((char)ch != '\r') // weird--it used to do \r\n translation
r = r + (char) ch;
} catch(java.io.IOException e) {
done = true;
} // try-catch
return r;
} // readLine
/** Read a string from the ConsoleMia. The string is terminated by a newline.
@param prompt The prompt string to display.
@return The input string (without the newline).
*/
public static String readLine(String prompt) {
printPrompt(prompt);
return readLine();
} // readLine
/** Read an integer from the ConsoleMia. The input is terminated by a newline.
@return The input value as an int.
*/
public static int readInt() {
return readInt("");
} // readInt
/** Read an integer from the ConsoleMia. The input is terminated by a newline.
@param prompt The prompt string to display.
@return The input value as an int.
*/
public static int readInt(String prompt) {
while(true) {
printPrompt(prompt);
try {
return Integer.valueOf(readLine().trim()).intValue();
// trim toglie gli spazi dalla fine
} catch(NumberFormatException e) {
System.out.println("Non e` un intero; riprova!");
} // try-catch
} // while
} // readInt
/** Read a floating point number from the ConsoleMia.
The input is terminated by a newline.
@return The input value as a double.
*/
public static double readDouble() {
return readDouble("");
} // readDouble
/** Read a floating point number from the ConsoleMia.
The input is terminated by a newline.
@param prompt The prompt string to display.
@return The input value as a double.
*/
public static double readDouble(String prompt) {
while(true) {
printPrompt(prompt);
try {
return Double.parseDouble(readLine().trim());
} catch(NumberFormatException e) {
System.out.println("Non e` un numero decimale; riprova!");
} // try-catch
} // while
} // readDouble
} // ConsoleMia