User input

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • maydoncillo
    New Member
    • Dec 2007
    • 1

    User input

    hi,
    How will i check if the user input is valid digit/numbers..?
    How will i do it in java..?
  • heat84
    New Member
    • Nov 2007
    • 118

    #2
    One soultion may be to use the Character class and then checking if the characters in a string are digits or not .

    Read the java docs , I am sure you will get the information you need.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by maydoncillo
      hi,
      How will i check if the user input is valid digit/numbers..?
      How will i do it in java..?
      Note that e.g. de Integer and Double class can convert a String to the type they
      wrap. If the String doesn't represent a valid wrapped type (int or double in this
      example) an NumberFormatExc eption is thrown.

      kind regards,

      Jos

      Comment

      • BigDaddyLH
        Recognized Expert Top Contributor
        • Dec 2007
        • 1216

        #4
        Demo: This reads from System.in, a line at a time and attempts to parse the line as an int.
        [CODE=Java]import java.io.*;

        public class NumberInputExam ple {
        public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(
        new InputStreamRead er(System.in));
        String line;
        while((line = in.readLine()) != null) {
        try {
        int n = Integer.parseIn t(line);
        System.out.form at("(%1$d)*(%1$ d)=%2$d%n", n, n*n);
        } catch (NumberFormatEx ception e) {
        System.out.form at("'%s' cannot be parsed%n", line);
        }
        }
        }
        }[/CODE]

        Comment

        Working...