A.hussain
A.hussain

Reputation: 27

Check if numerical values are valid integers

I have written some basic code below which allows me to get user input for games they have played. The user will input as follows "GameName:Score:Time". Once the user has inputted this I then convert the time and score to integers as they are inputted to a string. From this I need to ensure that the user has inputted a valid integer and I'm not to sure on how to do this.

    import java.util.Scanner;
import java.io.IOException;
import java.text.ParseException;
public class REQ2
{
    public static void main (String[] args) throws ParseException 
    {

     String playername;      
     String line;
     String[] list = new String[100];
     int count = 0;  
     int score;
     int time;
     int InvalidEntries;

     Scanner sc = new Scanner(System.in); 


      System.out.println("Please enter your name");

      playername = sc.nextLine();

      if(playername.equals(""))
      {
          System.out.println("Player name was not entered please try again");
          System.exit(0);
      }

      System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");

      while (count < 100){

             line = sc.nextLine();

             if(line.equals("quit")){
                  break;  
                  }

            if(!(line.contains(":"))){  
                System.out.println("Please enter achivements with the proper \":\" sepration\n");  
                break;
            }

             list[count]=line;
            System.out.println("list[count]" + list[count]);

            count++;

        for (int i=0; i<count; i++){
          line=list[i];
          String[] elements =line.split(":");   

          if (elements.length !=3){
                System.out.println("Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
                   break;
          }  


            score = Integer.parseInt(elements[1].trim());            
            time=Integer.parseInt(elements[2].trim());


        }         
    }   
}}

Upvotes: 1

Views: 120

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61128

The most powerful and flexible way is probably with regex:

final Pattern inputPattern = Pattern.compile("^(?<gameName>[^:]++):(?<score>\\d++):(?<time>\\d++)$")
final String line = sc.nextLine();
final Matcher matcher = inputPattern.matcher(line);
if(!matcher.matches()) {
    throw new IllegalArgumentException("Invalid input") //or whatever
}
final String gameName = matcher.group("gameName");
final int score = Integer.parseInt(matcher.group("score"));
final int time = Integer.parseInt(matcher.group("time"));

This way your regex both validates and parses your input.

The same is also possible with a MessageFormat:

final MessageFormat inputFormat = new MessageFormat("{0}:{1,number,integer}:{2,number,integer}")
final String line = sc.nextLine();
//throws an exception if input is invalid - possibly catch and report
final Object[] input = inputFormat.parse(line);
final String gameName = input[0];
//will be a long
final int score = (int) input[1];
final int time = (int) input[2];

Finally, the most simple way to do this, and with minimal changes to your current code is simply to catch the NumberFormatException that parseInt throws:

try {
    score = Integer.parseInt(elements[1].trim());
} catch(NumberFormatException ex) {
    //invalid input, emit error or exit
}

Upvotes: 4

Kevin W.
Kevin W.

Reputation: 1183

The way that I would do this is put the parsing in a try clock, and catch a NumberFormat exception, like so.

        try{
            score = Integer.parseInt(elements[1].trim());
        }
        catch(NumberFormatException e){
            //Deal with it not being an integer here
        }

You could also do this with regular expressions, but this is the way that seems the most straightforward to me.

Upvotes: 0

Related Questions