Java Input Validation for Number Range and Numeric Values Only With Counter

Java Input Validation for Number Range and Numeric values only with counter

As others have said to see if a String is a valid integer you catch a NumberFormatException.

try {
int number = Integer.parseInt(input);
// no exception thrown, that means its a valid Integer
} catch(NumberFormatException e) {
// invalid Integer
}

However I would also like to point out a code change, this is a prefect example of a do while loop. Do while loops are great when you want to use a loop but run the condition at the end of the first iteration.

In your case you always want to take the user input. By evaluating the while loops condition after the first loop you can reduce some of that duplicate code you have to do prior to the loop. Consider the following code change.

int count = 0;
String input;
int range;
do {
input = JOptionPane.showInputDialog(quantity);
try {
range = Integer.parseInt(input);
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Sorry that input is not valid, please choose a quantity from 1-9");
count++;
// set the range outside the range so we go through the loop again.
range = -1;
}
} while((range > 9 || range < 1) && (count < 2));

if (count == 2) {
JOptionPane.showMessageDialog(null,
"Sorry you failed to input a valid response, terminating.");
System.exit(0);
}
return range;

Validate text box input for numeric range 1-100

You should use double.TryParse because, if the input is not a valid double, it returns false instead of throwing an exception.

Public Function PopulateTestScores() as Boolean
Dim ok as Boolean
ok = CheckInput(txtStudent1Score1.Text, 0)
if not ok Then
txtStudent1Score1.Focus()
return ok
End if

ok = CheckInput(txtStudent1Score2.Text, 1)
if not ok Then
txtStudent1Score2.Focus()
return ok
End if
.....
return ok
End Function

private Function CheckInput(input as String, index as integer) as Boolean
Dim d as Double
Dim ok as Boolean
ok = double.TryParse(input, d)
if ok Then dblStudentTestScores(index) = d
return ok
End Function

The version of TryParse with two arguments expects the string to be in the same format of your locale (point/comma for decimals). If you want to work with different cultures then just use the appropriate TryParse overload that takes also the CultureInfo parameter.

For example, if you use the overload that takes a NumberStyles and a CultureInfo

ok = Double.TryParse(input, NumberStyles.None, CultureInfo.CurrentCulture, d)

TryParse will return false if the input doesn't match your CultureInfo and the correct convention for digit grouping.

A valid double like 10.1 in en-US culture is invalid the it-IT one where the correct input is 10,1

How can I validate a numeric input in java?

        while(true){
String userInput=JOptionPane.showInputDialog(null," Enter Positive Number");
if(userInput.matches("^\\d+(.\\d+)?$")){
double numberOfmiles=Double.parseDouble(userInput);
if (numberOfmiles <0){
JOptionPane.showMessageDialog(null, "Warning, enter positive numbers only")
}
else{
//successful input
break;
}
}
else{
JOptionPane.showMessageDialog(null, "Just positive numbers are allowed");
}

}

Loop to validate user input

import java.util.Scanner;

public class NewClass {

public static void main(String[] args)
{

int[] numArr = new int[3];
int sum=0,x;
Scanner keyboard = new Scanner(System.in);



for(int i=0; i<numArr.length; i++)
{
//check if between 1 and 10
System.out.println("Enter a number in the range 1 to 10: ");

//check if integer
while (!keyboard.hasNextInt())
{
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
x = keyboard.nextInt();
if(x>0 && x<=10)
numArr[i]=x;
else{
System.out.println("Retry Enter a number in the range 1 to 10:");
i--;
}

}


for (int counter=0; counter<numArr.length; counter++)
{
sum+=numArr[counter];
}
System.out.println("The sum of these numbers is "+sum);
}

}

How do I get java to only accept the user input of numbers 1-5?

I see one definitive error and one potential error.

if ((c!='1')||(c!='2')||(c!='3')||(c!='4')||(c!='5'))
panel.setStatus("Invalid input");
return;

Is equivalent to:

if ((c!='1')||(c!='2')||(c!='3')||(c!='4')||(c!='5')) {
panel.setStatus("Invalid input");
}
return;

Not sure if that's what you wanted. Your indentation suggests otherwise. Maybe it is just a mistake in the question. With the code given in the question, there is no difference, because return is the last statement of the block anyway. But something to keep in mind for future code if the early exit should happen conditionally and the other code skipped.

The definitive error is your boolean logic. They way you have written, the expression can never be false:

(c!='1') || (c!='2') || (c!='3') || (c!='4') || (c!='5')

If c is '1', then it is not equal to '2'. If c is '2' then it is not equal to '3'. Therefore the expression is always true for any input (a so-called tautology). The way you want to write it is either of the two:

(c!='1')&&(c!='2')&&(c!='3')&&(c!='4')&&(c!='5')
!((c=='1')||(c=='2')||(c=='3')||(c=='4')||(c=='5')

Or simpler:

if (!(c >= '1' && c <= '5'))

Making EditText accept a range of values without post validation

No need to do anything in xml.

Find EditText in code:

int minValue = 1;
int maxValue = 12;

EditText input = (EditText) findViewById(R.id.txtInput);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setFilters(new InputFilter[]
{
new InputFilterMinMax(minValue, maxValue),
new InputFilter.LengthFilter(String.valueOf(maxValue).length())
});
input.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

Code for InputFilterMinMax:

public class InputFilterMinMax implements InputFilter {

private int min, max;

public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
return "";
}

private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}

Hope will help you!

How to make HTML input tag only accept numerical values?

HTML 5

You can use HTML5 input type number to restrict only number entries:

<input type="number" name="someid" />

This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

<!DOCTYPE html>

See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.

JavaScript

Update: There is a new and very simple solution for this:

It allows you to use any kind of input filter on a text <input>,
including various numeric filters. This will correctly handle
Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations,
non-typeable keys, and all keyboard layouts.

See this answer or try it yourself on JSFiddle.

For general purpose, you can have JS validation as below:

function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}

<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>

If you want to allow decimals replace the "if condition" with this:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))

Source: HTML text input allow only numeric input

JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/



Related Topics



Leave a reply



Submit