joe8032
joe8032

Reputation: 11

How do I validate code that reads input of numbers within a range of 1,000 to 999,999?

I have it taking a number in the range from 1000 to 999999 also allowing for a comma. I now need to validate the code and provide the appropriate error messages.

import java.util.Scanner;

public class ConsoleReader {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    // get a connection to the keyboard 
    Scanner in = new Scanner(System.in); 

    // ask the user for input 
    System.out.print("Please enter an integer between 1,000 and 999,999: ");
    // read user's input 
    String number = in.next(); 

    // get the first part (no comma or thousands) 
    String firstPart = number.substring(0, number.length() - 4); 
    // get last three digits 
    String lastThreeDigits = number.substring(number.length() - 3); 

    // print the two without the comma 
    System.out.println(firstPart + lastThreeDigits);
}   
{
if (in.hasNextInt())
{
    String number = in.next();
}
else
{
    System.out.println("Please try again.");
}
}
}

Upvotes: 1

Views: 3659

Answers (7)

MadConan
MadConan

Reputation: 3767

There are two approaches you can take

  • Require strict input (e.g. "Enter a value between 1000 and 999999 - do not use commas!")
  • Allow more relaxed input and create validation rules based on expected patterns

The first approach is old school. You simply fail on any input that does not meet the rule. The benefit is that it makes the code easy to write and maintain. However, most users today expect software to be more flexible.

The second approach means you need to think hard about what types of input can be allowed. Simple cases are straight forward ("2450" or "23,333"). But what does it mean if the user enters "1K322"? Do you fail or treat it as if they mis-typed the comma? Or what about "23,23"? Technically, that's not a properly formatted number. Do you fail or assume 2323?

In any case, if you don't have access to some library that does the validation for you, I recommend:

  • if(input.length() > 7 || input.length() < 4) fail
  • get the char array (input.toCharArray())
    • validate that each character is between '0' and '9'
    • if char[n] == ',' make sure it is in the correct position (length - 4)
  • OR just use Smallhacker's answer.

Upvotes: 0

Deepak Bhatia
Deepak Bhatia

Reputation: 6276

If this is comma separated normal number,

    try
    {
        Number enteredValue = NumberFormat.getNumberInstance(java.util.Locale.US).parse(number);
        if(enteredValue.intValue()> 1000 && enteredValue.intValue() < 999999)
        {

        }

    }
    catch(NumberFormatException e) 
    {

    }
    catch (ParseException e) 
    {         
    }

Upvotes: 0

Slate
Slate

Reputation: 3704

Use if (num > 1000 && num < 999999)

You can validate commas using number.split(",")

boolean validateCommas(string input) {
  string[] arr = input.split(",");
  for (int i = 0; i < arr.length; i++) {
    if (i == 0) {
      // First section must be 3 or less.
      if (arr[0].length > 3) {
        return false;
      }
    } else {
      // Other sections must be 3.
      if (arr[i].length != 3) {
        return false;
      }
    }
  }
  return true;
}

then simply .replace(",", "") them out

Upvotes: 0

BambooleanLogic
BambooleanLogic

Reputation: 8171

Another way is to use regex to verify that it's a valid format, replace the comma, parse it to an int and ensure it's within the acceptable range.

String number = in.next(); 
if (number.matches("\\d{0,2}\\d\\,?\\d{3}") {
    int intNumber = Integer.parseInt(number.replace(",", "");
    if (number >= 1000 && number <= 999999) {
        ...
    }
}

Upvotes: 3

AurA
AurA

Reputation: 12373

Use number format to get the long value and then you can compare

String number = in.next(); 

NumberFormat nf = new DecimalFormat("#,###");
long d = 0;
try {
    d = (Long) nf.parse(number);
} catch (ParseException e) {
    e.printStackTrace();
}

Then test using

if(d >= 1000 && d <= 999999)

Upvotes: 0

Christian Kullmann
Christian Kullmann

Reputation: 578

Well, you should check the input for length. If i enter a number < 1000, an exception will be thrown due to

String firstPart = number.substring(0, number.length() - 4);

For input "1", this code part will be:

String firstPart = number.substring(0, -3);

Same goes for

 String lastThreeDigits = number.substring(number.length() - 3); 

You ASSUME that the number has the correct length but you need to check that.

Maxim had the right idea with the wrong outcome: Check for it like this:

if(number.length > 3 && number.length < 9)

Upvotes: 0

alain.janinm
alain.janinm

Reputation: 20065

You can use a NumberFormat to create a Number (check this answer) and get it's int value then you just have to check the boundaries with a simple if test if(num >= 1000 && num <= 999999)

Upvotes: 0

Related Questions