Thursday, 27 February 2014

Converting Strings to Numbers in Java

The following program asks the user for a string of characters and converts them to a number:

andrew@UBUNTU:~/Java$ cat prog32.java
import java.io.*;
public class prog32
{
public static void main(String[] args)
  {
  System.out.print("Type a number: ");
  InputStreamReader isr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(isr);
  try
    {
    int a = Integer.parseInt(br.readLine());
    System.out.println("You entered " + a);
    }
  catch (IOException test)
    {
    System.out.println("I/O error");
    }
  }
}
andrew@UBUNTU:~/Java$ javac prog32.java
andrew@UBUNTU:~/Java$ java prog32
Type a number: 27
You entered 27
andrew@UBUNTU:~/Java$

If the user enters an invalid value, the program falls over:

andrew@UBUNTU:~/Java$ java prog32
Type a number: blah
Exception in thread "main" java.lang.NumberFormatException: For input string: "blah"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:481)
    at java.lang.Integer.parseInt(Integer.java:514)
    at prog32.main(prog32.java:11)
andrew@UBUNTU:~/Java$

To stop this happening, you can trap the error and display a suitable message like this:

andrew@UBUNTU:~/Java$ cat prog33.java
import java.io.*;
public class prog33
{
public static void main(String[] args)
  {
  System.out.print("Type a number: ");
  InputStreamReader isr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(isr);
  try
    {
    int a = Integer.parseInt(br.readLine());
    System.out.println("You entered " + a);
    }
  catch (IOException test1)
    {
    System.out.println("I/O error");
    }
  catch (NumberFormatException test2)
    {
    System.out.println("Invalid value");
    }
  }
}
andrew@UBUNTU:~/Java$ javac prog33.java
andrew@UBUNTU:~/Java$ java prog33
Type a number: 34
You entered 34
andrew@UBUNTU:~/Java$ java prog33
Type a number: blah
Invalid value
andrew@UBUNTU:~/Java$