Input validation in setter method [duplicate] - java

This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 3 years ago.
How can I make my setter method public void setYear(String year) check if the input is a number or not? It's for a class exercise. I'm just trying to understand why/how to do this. I don't know why, but it has to be string year, and I need to make sure that only a number can be used.
For example I have:
public void setColour(String colour) {
colour = colour;
}

public void setYear(String year) {
if (Integer.parseInt(year) >= 0) {
//Do stuff here
}
}
Use Integer.parseInt(String s) to check if String year can be convert to an Integer greater or equal to zero (logically, a year can not be negative). If the input can not be converted to an Integer, it will throw a NumberFormatException.

I can propose 2 ways of doing this.
Suppose the string you need to validate is strYear and you consider valid all integer values >= 0.
The 1st is by forcing the string to be casted to an integer and catching any error thrown:
int year = -1;
try {
year = Integer.parseInt(strYear);
} catch (NumberFormatException e) {
e.printStackTrace();
}
boolean validYear = (year >= 0);
The 2nd is eliminating all non numeric chars in the string and compare the result to the original string. If they are the same then the string consists only of digits:
strYear = strYear.trim();
String strOnlyDigits = strYear.replaceAll("\\D", "");
boolean validYear = (!strYear.isEmpty() && strYear.equals(strOnlyDigits));

public int year;
public void setYear(String year){
try {
year = Integer.parseInt(year);
} catch(Exception e) {
e.printStackTrace();
}
}
You can use try and catch to check if the input is a number. In here, you are trying to parse the String into integer. If it only contains a number, it will be able to convert it successfully. On the other hand, if it has some other characters, it will stop and you will get an exception. Try and catch prevents your program from crashing.
At the same time, you can try regular expression to check if it only contains number.
String regex = "[0-9]+";
year.matches(regex );

Related

Check if any part of a string input is not a number

I couldnt find an answer for this in Java, so I'll ask here. I need to check if 3 parts of a string input contains a number (int).
The input will be HOURS:MINUTES:SECONDS (E.g. 10:40:50, which will be 10 hours, 40 minutes and 50 seconds). So far I am getting the values in String[] into an array by splitting it on :. I have parsed the strings into ints and I am using an if statement to check if all 3 parts is equal or larger than 0. The problem is that if I now use letters I will only just get an error, but I want to check if any of the 3 parts contains a character that is not 0-9, but dont know how.
First I thought something like this could work, but really dont.
String[] inputString = input.split(":");
if(inputString.length == 3) {
String[] alphabet = {"a","b","c"};
if(ArrayUtils.contains(alphabet,input)){
gives error message
}
int hoursInt = Integer.parseInt(inputString[0]);
int minutesInt = Integer.parseInt(inputString[1]);
int secondsInt = Integer.parseInt(inputString[2]);
else if(hoursInt >= 0 || minutesInt >= 0 || secondsInt >= 0) {
successfull
}
else {
gives error message
}
else {
gives error message
}
In the end I just want to check if any of the three parts contains a character, and if it doesnt, run something.
If you are sure you always have to parse a String of the form/pattern HH:mm:ss
(describing a time of day),
you can try to parse it to a LocalTime, which will only work if the parts HH, mm and ss are actually valid integers and valid time values.
Do it like this and maybe catch an Exception for a wrong input String:
public static void main(String[] arguments) {
String input = "10:40:50";
String wrongInput = "ab:cd:ef";
LocalTime time = LocalTime.parse(input);
System.out.println(time.format(DateTimeFormatter.ISO_LOCAL_TIME));
try {
LocalTime t = LocalTime.parse(wrongInput);
} catch (DateTimeParseException dtpE) {
System.err.println("Input not parseable...");
dtpE.printStackTrace();
}
}
The output of this minimal example is
10:40:50
Input not parseable...
java.time.format.DateTimeParseException: Text 'ab:cd:ef' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalTime.parse(LocalTime.java:441)
at java.time.LocalTime.parse(LocalTime.java:426)
at de.os.prodefacto.StackoverflowDemo.main(StackoverflowDemo.java:120)
I would personally create my own helper methods for this, instead of using an external library such as Apache (unless you already plan on using the library elsewhere in the project).
Here is an example of what it could look like:
public static void main(String[] arguments) {
String time = "10:50:45";
String [] arr = time.split(":");
if (containsNumbers(arr)) {
System.out.println("Time contained a number!");
}
//You can put an else if you want something to happen when it is not a number
}
private static boolean containsNumbers(String[] arr) {
for (String s : arr) {
if (!isNumeric(s)) {
return false;
}
}
return true;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
containsNumbers will take a String array as an input and use an enhanced for loop to iterate through all the String values, using the other helper method isNumeric that checks if the String is a number or not using regex.
This code has the benefit of not being dependent on Exceptions to handle any of the logic.
You can also modify this code to use a String as a parameter instead of an array, and let it handle the split inside of the method instead of outside.
Note that typically there are better ways to work with date and time, but I thought I would answer your literal question.
Example Runs:
String time = "sd:fe:gbdf";
returns false
String time = "as:12:sda";
returns false
String time = "10:50:45";
returns true
You can check the stream of characters.
If the filter does not detect a non-digit, return "Numeric"
Otherwise, return "Not Numeric"
String str = "922029202s9202920290220";
String result = str.chars()
.filter(c -> !Character.isDigit(c))
.findFirst().isEmpty() ? "Numeric"
: "Not Numeric";
System.out.println(result);
If you want to check with nested loop you can see this proposal:
Scanner scanner = new Scanner(System.in);
String [] inputString = scanner.nextLine().split(":");
for (int i = 0; i < inputString.length; i++) {
String current = inputString[i];
for (int k = 0; k < current.length(); k++) {
if (!Character.isDigit(current.charAt(k))) {
System.out.println("Error");
break;
}
}
}
you could use String.matches method :
String notANum= "ok";
String aNum= "7";
if(notANum.matches("^[0-9]+$") sop("no way!");
if(aNum.matches("^[0-9]+$") sop("yes of course!");
The code above would print :
yes of course
The method accepts a regex, the one in the above exemple is for integers.
EDIT
I would use this instead :
if(input.matches("^\d+:\d+:\d+$")) success;
else error
You don't have to split the string.
I tried to make your code better, take a look. You can use Java regex to validate numbers. also defined range for time so no 24:61:61 values is allowed.
public class Regex {
static boolean range(int timeval,int min,int max)
{
boolean status=false;
if(timeval>=min && timeval<max)
{status=true;}
return status;
}
public static void main(String[] args) {
String regex = "[0-9]{1,2}";
String input ="23:59:59";
String msg="please enter valid time ";
String[] inputString = input.split(":");
if(inputString[0].matches(regex) && inputString[1].matches(regex) && inputString[2].matches(regex) )
{
if(Regex.range(Integer.parseInt(inputString[0]), 00, 24) &&Regex.range(Integer.parseInt(inputString[1]), 00, 60) && Regex.range(Integer.parseInt(inputString[2]), 00, 60))
{msg="converted time = " + Integer.parseInt(inputString[0]) + " : " +Integer.parseInt(inputString[1])+ " : " +Integer.parseInt(inputString[2]) ;}
}
System.out.println(msg);
}
}

how add the exception handling after accpeting input in JTextField in java

This is the GUI form that I have created. The value is obtained from the text field and it is stored in the new variable. For some value, it needs to be converted into the integer type. I have converted the value to the integer type, but I am trying to handle the exception when the user doesn't enter any value in the text field. for that, I have used if statement. And for the next exception is when the user enters the string value into the integer field. So I am not been able to handle this exception properly. please help me in doing so.
public void addSeniorDev(){
String plat=txt1.getText();
String name = txt2 .gettText();
String hours = txt3.getText();
String period = txt4.getText();
String salary = txt5.getText();
if( plat==("") || name==("") || hours==("")|| period==("")|| salary==
("")){
JOptionPane.showMessageDialog(DA,"The field are left empty:");
}try{
int hours1 = Integer.parseInt(hours);
int salary1 = Integer.parseInt(salary);
int period1 = Integer.parseInt(period);
}catch(ArithmeticException e){
JOptionPane.showMessageDialog(DA,"only number are accepted");
}
}
First of all you cannot compare Strings like that. Use equals method or isEmpty() to check if String is empty. Second thing is that if String is not parsable to Integer it throws NumberFormatException not an ArithmeticException according to documentation:
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
public void addSeniorDev(){
String plat=txt1.getText();
String name = txt2 .gettText();
String hours = txt3.getText();
String period = txt4.getText();
String salary = txt5.getText();
if(plat.isEmpty() || name.isEmpty() || hours.isEmpty() || period.isEmpty()|| salary.isEmpty()) { // changed String comparison
JOptionPane.showMessageDialog(DA,"The field are left empty:");
}try{
int hours1 = Integer.parseInt(hours);
int salary1 = Integer.parseInt(salary);
int period1 = Integer.parseInt(period);
}catch(NumberFormatExceptione){ // Changed exception type
JOptionPane.showMessageDialog(DA,"only number are accepted");
}
}
It is never advisable to do like this
plat==("")
do it like this
StringUtils.isEmpty(plat)
and instead of putting integer parsing under try catch you can avoid it with
StringUtils.isNumeric(hours)
and if this condition comes out to false you can take the required action.
Note : StringUtils is available under import apache.commons.lang3

String input and if [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public class LabWork {
private String yourStatus;
private int yourIncome;
private double tax;
public int calculateTax () {
if (yourStatus = "Married" && yourIncome <= 2000) {
tax = yourIncome/10;
}
else if (yourStatus = "Married" && yourIncome > 2000) {
tax = 3*yourIncome/20;
}
else if (yourStatus = "Single" && yourIncome <=2000) {
tax = 17*yourIncome/100;
}
else
tax = 22*yourIncome/100;
}
public double getTax () {
return tax;
}
}
this is my first code and I have a tester class to use this like:
import java.util.Scanner;
public class UseLab3Work {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is your status? ");
String yourStatus = keyboard.next();
System.out.println("What is your incomew? ");
int yourIncome = keyboard.nextInt();
}
}
However, in the first program, I'm getting an error like "String cannot be converted to boolean" at line 7,10 and 14. Then how should I use if with String? For example I have input in tester and when I write there Married, the program should calculate tax related to my String input.
I first would have thought to mark this a duplicate, since you are comparing your Objects wrong, but it's a step further.
if (yourStatus = "Married" )
Here, you don't compare the values of the String, you actually just assign it.
if (yourStatus == "Married")
This would be better, but will produce false results. After all, the == operator is used for referential comparison, while you want to compare values.
if (yourStatus.equals("Married")) (or if (yourStatus.equalsIgnoreCase("Married")) )
would be better, since this is the correct way to compare the values of Strings.
An even better way would be:
if ( "Married".equals(yourStatus))
In the other order, if yourStatus is null, it will throw a NullPointerException, which you avoid by calling equals (or equalsIgnoreCase) on the String literal.

How to check if a string is a valid integer? [duplicate]

This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 8 years ago.
I have:
op1 = Integer.parseInt(jTextField1.getText());
op2 = Integer.parseInt(jTextField2.getText());
However, I want to check first whether the text fields' values can be assigned to integer variables. How do I do that?
I've been going through this for a long time, so, if this was already asked here, forgive me
You can't do if (int i = 0), because assignment returns the assigned value (in this case 0) and if expects an expression that evaluates either to true, or false.
On the other hand, if your goal is to check, whether jTextField.getText() returns a numeric value, that can be parsed to int, you can attempt to do the parsing and if the value is not suitable, NumberFormatException will be raised, to let you know.
try {
op1 = Integer.parseInt(jTextField1.getText());
} catch (NumberFormatException e) {
System.out.println("Wrong number");
op1 = 0;
}
This works for me. Simply to identify whether a String is a primitive or a number.
private boolean isPrimitive(String value){
boolean status=true;
if(value.length()<1)
return false;
for(int i = 0;i<value.length();i++){
char c=value.charAt(i);
if(Character.isDigit(c) || c=='.'){
}else{
status=false;
break;
}
}
return status;
}
parseInt throws NumberFormatException if it cannot convert the String to an int. So you should surround the parseInt calls with a try catch block and catch that exception.
Basically, you have to decide to check if a given string is a valid integer or you simply assume a given string is a valid integer and an exception can occur at parsing.

How to check the type of a value in Java? [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 9 years ago.
I'm making a program where I want the user to input a value into a variable. After it is inputted I want to check the value type, but I don't know how. It looks a bit like this:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int num1;
num1 = scanner.nextInt();
I want some way of checking the type of num1, so that I can make sure the user has inputted a usable value i.e. to make sure they haven't inputted a string such as "qwerty" into the integer variable, so that I can go on to catch the error if they have, rather than end up with a java.util.InputMismatchException. I've tried:
if(num1 instanceof java.lang.String)
but it doesn't fix the error and it doesn't work for integers either.
Any ideas on how to fix this?
public boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
Do as the others mentioned and use scanner.next() to retrieve a string. Afterwards you can use the above code snippet to check if a string is an Integer.
For a double it looks pretty similiar:
boolean isDouble(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Java is a static typed language so scanner.nextInt(); will always return int.
If you want the return type to be String call scanner.next()

Categories

Resources