[Java] Checking if input is valid.

Discussion in 'Programming' started by killaklown, Jan 23, 2008.

  1. #1
    How can i check if input it valid, and if it isnt, request the user to put in valid information?

    		studentName = JOptionPane.showInputDialog("Student Mark Calculator \n Enter Your Name:");
    // Would check if the studentName contains something, if not, request again.
    
    		temp = JOptionPane.showInputDialog("Student Mark Calculator \n Enter Your Assignment Mark (140 Max):");
    		assignmentMark = Integer.parseInt(temp);
    // Would check if the user entered a number. If its not a number, or nothing at all, request again.
    
    		temp = JOptionPane.showInputDialog("Student Mark Calculator \n Enter Your Mid-Term Exam Mark (60 Max):");
    		midExamMark = Integer.parseInt(temp);
    // Would check if the user entered a number. If its not a number, or nothing at all, request again.
    
    		temp = JOptionPane.showInputDialog("Student Mark Calculator \n Enter Your Final Exam Mark (85 Max):");
    		fExamMark = Integer.parseInt(temp);
    // Would check if the user entered a number. If its not a number, or nothing at all, request again.
    
    Code (markup):

    I know how it would be done in php (sucks learning a new language at first, lol) But with java, as soon as lets say 'Me' is entered, it crashes.
     
    killaklown, Jan 23, 2008 IP
  2. webmaster_TSU

    webmaster_TSU Peon

    Messages:
    449
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You might have to do something like this:

    
    boolean boolInputOK = true;
    try {
         assignmentMark = Integer.parseInt(temp);
    } catch (NumberFormatException e) {       
         //System.out.println(temp + " is not a number! " + e.getMessage());
         boolInputOK = false;
    }
    Code (markup):
    Around each int parse. Then, if boolInputOK == false at the end, get the input again.

     
    webmaster_TSU, Jan 23, 2008 IP
  3. Arkserver

    Arkserver Banned

    Messages:
    2,533
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    0
    #3
    always check for null values before processing the data. Or you might get a NPE.
     
    Arkserver, Jan 26, 2008 IP