I am trying to validate input from a textfield so that it only contains characters from a-z. I am using the following method to validate if the input is an int:
//VALIDATE IF INPUT IS NUMERIC.
public static boolean isInt(JFXTextField txtUserInput, String userInput) {
try {
int intValidation = Integer.parseInt(userInput);
txtUserInput.setStyle("-fx-border-color: ; -fx-border-width: 0px ;");
return true;
} catch(NumberFormatException exception) {
showErrorMsg("Invalid Input:", "Please enter a numeric-only value");
txtUserInput.setStyle("-fx-border-color: RED; -fx-border-width: 1px ;");
return false;
}
}
How can I achieve this using a String? I know there is a different way of doing this using an if statement but I was wondering if I can catch an exception like in the example above.
Thanks
Use regex:
if (!userInput.matches("[a-z]+"))
// Has characters other than a-z
If you want to allow uppercase too:
if (!userInput.matches("[a-zA-Z]+"))
// Has characters other than a-z or A-Z
You can use matches with regex so if you want to check your input is an int or not you can use:
String userInput = ...;
if(userInput.matches("\\d+")){
System.out.println("correct");
}else{
System.out.println("Not correct");
}
If you want to check if the input contain only alphabetic, you can use :
if(userInput.matches("[a-zA-Z]+")){
System.out.println("correct");
}else{
System.out.println("Not correct");
}
If you want to check if your input contains alphanumeric you can use :
if(userInput.matches("[a-zA-Z0-9]+")){
System.out.println("correct");
}else{
System.out.println("Not correct");
}
You could use something like:
if (!userInput.matches(".*[^a-z].*")) {
// Do something
}
Alternative solution to #Bohemian♦ to allow uppercase:
if (!userInput.toLowerCase().matches(".*[^a-z].*")) {
// Do something
}
A similar method, according to your source:
public static boolean containsAZ(JFXTextField txtUserInput) {
if (!txtUserInput.getText().toLowerCase().matches(".*[^a-z].*"))
return true;
else
System.err.println("Input is not containing chars between A-Z");
return false;
}
There your question is, if it's possible to throw/catch an exception, you could do the following:
public static boolean containsAZ(JFXTextField txtUserInput) {
try {
if (!txtUserInput.toLowerCase().matches(".*[^a-z].*")) {
return true;
} else
throw new MyException("Something happened");
} catch (MyException e) {
e.printStackTrace();
}
return false;
}
Considering that you'll need a class:
class MyException extends Exception {
public MyException(String e) {
System.out.println(e);
}
}
An abstract solution would be:
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
throw new MyException ("Something happened")
Catch as:
catch (MyException e)
{
// Do something
}
For more info, check this for regex.
Related
I have a sample program which registers people for an airline.
At the Registration class, on the selectSeats method, I have a try catch block, where the catch statement should catch InputMismatchException in case the user inputs a non numeric value.
However, the reinput operation isn't happening, so instead, when an exception happens, the program just throws the error message and proceeds to the end (which leads to unexpected results)
This is the method in question
public void seleccionarAsiento() {
boolean malaSeleccion = true;
do{
try{
System.out.println("\n\n Digite el número de asiento del 0 hasta el 20");
while (malaSeleccion) {
//Selección del hashSet correspondiente a cada vuelo mediante uso de la variable polimorfica "asientos".
if(this.destino.equals("Nicaragua")) {
asientos = asientosNCA;
}
else if (this.destino.equals("Panama") || this.destino.equals("Panamá")) {
asientos = asientosPNA;
}
this.asiento = input.nextInt(); //The part causing the issue
if(this.asiento < 0 || this.asiento > 20) {
System.out.println("\nSelect a seat between 0 and 20.");
} else if (asientos.contains(this.asiento)) {
System.out.println("\nSeat taken, select another one.");
} else if (this.asiento >= 0 && this.asiento <= 20 && asientos.contains(this.asiento) == false) {
asientos.add(this.asiento);
continuarCiclo = false;
malaSeleccion = false;
}
}
} // Fin de bloque try
//Bloque catch para prevenir un input no numerico.
catch (InputMismatchException inputMismatchException) {
System.out.println("Not numeric value, try again.");
input.nextLine();
}
In case this is relevant, since I'm not sure if this could be related to a problem with Inheritance (but I doubt it because the exception is being caught)
This is the start of the class where that method is, and an extension to Exception I added.
public class RegistroCompra {
Scanner input = new Scanner(System.in);
private String destino;
private int asiento;
private boolean continuarCiclo = true;
public static HashSet<Integer> asientosNCA = new HashSet(21);
public static HashSet<Integer> asientosPNA = new HashSet(21);
HashSet<Integer> asientos = null;
class ExcepcionRegistro extends Exception {
ExcepcionRegistro(String s) {
super(s);
}
}
} while (continuarCiclo == true); // Fin de bloque Do
Edit: I solved the issue by making the method recursive in the catch block.
So if it catches the inputmismatchexception (because it was catching it), it cleans the buffer from the invalid input with input.nextLine() and then, the function calls itself again to restart the selection process.
Do it as follows:
public void selectSeat() {
boolean valid = true;
do {
System.out.println("Enter the seat number from 0 to 20");
// ...
try {
this.asient = Integer.parseInt(input.nextLine());
// ...
} catch (InputMismatchException inputMismatchException) {
System.out.println("This is not a numerical value, try again.");
valid = false;
}
} while (!valid);
}
The exception may not the instance of InputMismatchException. You could try add Exception e to take a look the real exception.
catch (InputMismatchException inputMismatchException) {
System.out.println("Este no es un valor númerico, intente de nuevo.");
input.nextLine();
}
catch (Exception e) {
exception.printStackTrace()
input.nextLine();
}
I'm thinking how to do when I click the button first time it will show the result. After that i click the second time then the button will clear the result.
Example: First time Click, It will Calculate
R.id.Equal: calculate(true);
Calculate's Method
private void calculate(boolean IsEqualClick) {
String input = getinput();
try {
if (!isEmpty()) {
if (input.contains("x")) {
input.replaceAll("x", "*");
}
}
Expression expression = new ExpressionBuilder(input).build();
double result = expression.evaluate();
if (IsEqualClick) {
inputtext.setText(String.valueOf(twoDForm.format(result)));
resulttext.setText("");
} else {
resulttext.setText(String.valueOf(twoDForm.format(result)));
}
} catch (Exception e) {
stateError = true;
isNumber = false;
}
}
I can't think of how to write a code If i Click second time, it will delete. should I use the if statement again to progress it?
There is no need to check that isEqualClick if you have properly written the switch statement plus it is hardcoded so there is no meaning behind it.
Now for your solution do something like this:-
Declare a global variable boolean toCalculate = true;, this variable will check if we have to calculate or we have to clear the box;
Function call for calculate();
R.id.Equal: calculate();
The calculate() function:-
private void calculate() {
if (toCalculate) {
String input = getinput();
try {
if (!isEmpty()) {
if (input.contains("x")) {
input.replaceAll("x", "*");
}
}
Expression expression = new ExpressionBuilder(input).build();
double result = expression.evaluate();
/*->Write all your code for printing the answer here<-*/
/*for eg:- result.setText(String.valueOf(twoDForm.format(result)))*/
toCalculate = false;
} catch (Exception e) {
stateError = true;
isNumber = false;
}
} else {
/*->Write all your code for clearing the answer here<-*/
/*for eg:- result.setText("")*/
toCalculate = true;
}
}
Or you can do something like this and you don't have to change the function like we did above:-
R.id.Equal: if(toCalculate)
{
calculate();
toCalculate = false;
}else
{
/*->Write all your code for clearing the answer here<-*/
/*for eg:- result.setText("")*/
toCalculate = true;
}
break;
Is there a way to create a regex, that will check for proper 'closure' of a checkstyle (which begins with //)?
// CHECKSTYLE:OFF
protected void doSomething() {
}
// CHECKSTYLE:ON
// CHECKSTYLE:OFF
protected void doSomethingElse() {
// CHECKSTYLE:ON
}
If there is a typo in the first CHECKSTYLE:ON, the rest of checkstyles will be ignored.
I don't know if a pure regex would be appropriate here. Your problem is the really the stuff with which parsers are concerned. Actually, I don't even know how we would detect // CHECKSTYLE:ON with a typo in it. But, one option here would be to simply scan your file line by line, and fail if we ever encounter two // CHECKSTYLE:OFF in a row. If that happens, then it implies that either the ON checkstyle was completely omitted, or it was mispelled.
static final String CHECK_ON = "// CHECKSTYLE:ON";
static final String CHECK_OFF = "// CHECKSTYLE:OFF";
File file = new File("your_input.ext");
boolean checkstyleIsOn = false;
try {
Scanner sc = new Scanner(file);
int lineNum = 0;
while (sc.hasNextLine()) {
++lineNum;
String line = sc.nextLine();
if (CHECK_OFF.equals(line)( {
if (!checkStyleIsOn) {
System.out.println("Found extra checkstyle off at line " + lineNum);
break;
}
else {
checkStyleIsOn = false;
}
}
if (CHECK_ON.equals(line)( {
if (checkStyleIsOn) {
System.out.println("Found extra checkstyle on at line " + lineNum);
break;
}
else {
checkStyleIsOn = true;
}
}
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
I'm trying to validate german postcodes in a input form.
But somehow i get stuck in line 15 and my function is just printing "Give me input" in an endless loop.
I expected that sc_plz.nextLine() would be a blocking function but somehow it's not.
import View.AddressView;
import java.io.IOException;
import java.util.Scanner;
public class AddressController {
AddressView view = new AddressView();
public Address addAddress()throws IOException{
//other input questions
Scanner sc_plz = new Scanner(System.in);
int code = 0;
while (!validatePostcode(code))
view.askPostcode(); //simple System.out.println("Input something")
String postcode = sc_plz.nextLine();
try {
code = Integer.parseInt(postcode);
}
catch (NumberFormatException e){
view.invalidData(); //warning about not got a number
}
//other input questions
}
private boolean validatePostcode(int plz) throws IOException {
//legal postcodenumbers are between 01000 -99999
if (1000 <= plz && plz <= 99999){
return true;
}
else {
return false;
}
}
}
Did you forget brackets for your while statement? As it is right now it will always do whatever is in view.askPostcode();. I imagine this is what it should look like:
while (!validatePostcode(code)) {
view.askPostcode(); //simple System.out.println("Input something")
String postcode = sc_plz.nextLine();
try {
code = Integer.parseInt(postcode);
} catch (NumberFormatException e){
view.invalidData(); //warning about not got a number
}
}
I currently have a validation method which returns a boolean based upon whether a given String is a valid Double, Float, Integer, Long, or Short. Whilst this seems to catch cases such as "asdf" as being an invalid string, it seems to fail when there is an invalid numeric string which starts with a series of numbers e.g.: "33asd". The method is shown below:
public static boolean isNumeric(String str, Class<? extends Number> cl) {
try {
if (cl.equals(Byte.class)) {
Byte.parseByte(str);
} else if (cl.equals(Double.class)) {
if (NumberUtils.convertStringToDouble(str, "###,###") == null) {
return false;
}
} else if (cl.equals(Float.class)) {
Float.parseFloat(str);
} else if (cl.equals(Integer.class)) {
Integer.parseInt(str);
} else if (cl.equals(Long.class)) {
Long.parseLong(str);
} else if (cl.equals(Short.class)) {
Short.parseShort(str);
}
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
The NumberUtils.convertStringToDouble method used above is:
/**
* #param number
* - The String to convert.
* #param format
* - The format of the string representation of the double (e.g:
* "###,###.00")
* #return The String as a java.lang.Double if its valid; otherwise null.
*/
public static Double convertStringToDouble(String number, String format) {
try {
NumberFormat num = new DecimalFormat(format);
return num.parse(number).doubleValue();
} catch (ParseException e) {
return null;
} catch (NullPointerException ne) {
return null;
}
}
As documented for DecimalFormat.parse,
parsing does not necessarily use all characters up to the end of the string
So, by the time the parser reaches the alphabet character, it already has something which parses into a legal number, and simply stops there.