Reading Numbers

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

Comments are closed.