Posted By

bcmoney on 08/17/12


Tagged

input io console output


Versions (?)

ConsoleReader.java


 / Published in: Java
 

URL: http://www.cs.indiana.edu/classes/a202-sbog/ConsoleReader.java

The infamous ConsoleReader, without which I wouldn't have learned much in Java in University, as it took a while to get my head around how input/output works in an object-oriented programming context.

Thanks to Indiana U for posting since my school's (AcadiaU) has since been taken down.

  1. /**
  2.  * ConsoleReader.java
  3.  * Reads input from the keyboard.
  4.  * This is useful for teaching students about basic input and
  5.  * output without scaring them away with the gritty details.
  6.  * EXAMPLE:
  7.  * ConsoleReader console = new ConsoleReader(System.in);
  8.  * String txt = console.readLine(); // returns a String
  9.  * -or-
  10.  * int num = console.readInt(); // returns an int
  11.  * -or-
  12.  * Double num = console.readDouble(); // returns a double
  13.  */
  14. import java.io.InputStreamReader;
  15. import java.io.InputStream;
  16. import java.io.BufferedReader;
  17. import java.io.IOException;
  18.  
  19. public class ConsoleReader {
  20. private BufferedReader reader;
  21.  
  22. public ConsoleReader(InputStream inStream) {
  23. reader = new BufferedReader(new InputStreamReader(inStream));
  24. }
  25.  
  26. public String readLine() {
  27. String inputLine = "";
  28.  
  29. try {
  30. inputLine = reader.readLine();
  31. }
  32. catch(IOException e) {
  33. System.out.println(e);
  34. System.exit(1);
  35. }
  36.  
  37. return inputLine;
  38.  
  39. }
  40.  
  41. public int readInt() {
  42. String inputString = readLine();
  43. int n = Integer.parseInt(inputString);
  44. return n;
  45. }
  46.  
  47. public double readDouble() {
  48. String inputString = readLine();
  49. double x = Double.parseDouble(inputString);
  50. return x;
  51. }
  52.  
  53. }

Report this snippet  

You need to login to post a comment.