Reading Numbers | Building Blocks Java (original) (raw)

Often strings aren’t enough. A lot of times you’ll want to ask the user for a number as input. All user input comes in as strings so we need to convert the string into a number.

Next we promised to write a getNextInteger() method that will accept an integer from the user. Here it is:

  static int getNextInteger() {

    String line;

    DataInputStream in = new DataInputStream(System.in);
    try {
      line = in.readLine();
      int i = Integer.valueOf(line).intValue();
      return i;
    }
    catch (Exception e) {
      return -1;
    }

  } // getNextInteger ends here

This entry was posted on Wednesday, July 29th, 2009 at 9:22 am and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.