Java registration simple checker - java

I have a simple password and text area checker for a registration page. Here all the text area MUST be filled, otherwise a popup JOptionPane. AND the password and the re-entered password (confirm password) should be equal otherwise warning.
I don't know how to do this.
Code:
private boolean check() {
boolean isEmpty=false;
if(nickNametxt.getText().equals("") || pwdTxt.getText().equals("") ||
logintxt.getText().equals("") || rePwdTxt.getText().equals("")){
JOptionPane.showMessageDialog(null, "Please fill all the fields before proceeding");
if (pwdTxt != rePwdTxt){
JOptionPane.showMessageDialog(null, "Wrong Password");
}
isEmpty = true ;
}
return isEmpty ;
}

Try with the following code snippet. The second if condition has been modified from != to .equals as != will verify object reference.
private boolean check(){
boolean isEmpty = false;
String nickName = nickNametxt.getText();
String login = logintxt.getText();
String pwd = pwdTxt.getText();
String rePwd = nickNametxt.getText();
isEmpty = true;
if(!((null != nickName && !nickName.isEmpty()) && (null != login && !login.isEmpty())
&& (null != pwd && !pwd.isEmpty()) && (null != rePwd && !rePwd.isEmpty()))){
JOptionPane.showMessageDialog(null, "Please fill all the fields before proceeding");
isEmpty = true;
}else if(!pwd.equals(rePwd)){
JOptionPane.showMessageDialog(null, "Wrong Password");
//Depending on your usecase - place it here or not
//isEmpty = true;
}
return isEmpty;
}

Related

Cleaning code with too much conditionals

I've found this ugly piece of code from some time ago:
#FXML
private void buttSellAction(ActionEvent event){
InfoTip infoTip = new InfoTip();
if(comboPizza.getValue() != null){
if(comboPizzaSize.getValue() != null){
PizzaData selectedPizza = getPizzaData(comboPizza.getValue());
PizzaSizeData selectedPizzaSize = getPizzaSizeData(comboPizzaSize.getValue());
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
if( selectedPizza != null ){
if(groupDelivery.getSelectedToggle().equals(radioNo)){ // sale without delivery
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirm");
alert.setHeaderText("Total cost: " + String.format("%.2f", selectedPizza.getPrice() + selectedPizzaSize.getPrice()));
alert.setContentText("Proceed with sale?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
insertSale(timestamp, currentUser.getLogin(), selectedPizza.getID(),
selectedPizzaSize.getSize(), false, selectedPizza.getPrice() + selectedPizzaSize.getPrice());
infoTip.getInfoTip().setId("greenInfoTip");
infoTip.showTip((Button)event.getSource(), " Saved ");
}
}else{ //Sale with delivery
String adress = textFAdress.getText();
String clientName = textFClientName.getText();
String telephone = textFTelephone.getText();
String deliveryCost = textFCost.getText();
boolean isAdressOK = ((adress.length() < 51) && (adress.isEmpty() == false))? true: false;
boolean isClientNameOK = (clientName.length() < 36)? true: false;
boolean isTelephoneOK = ((telephone.length() < 21) && (telephone.isEmpty() == false))? true: false;
boolean isCostOK;
try{ Double.valueOf(deliveryCost); isCostOK = true; }
catch(NumberFormatException exception){ isCostOK = false; }
if(isAdressOK == true){
if(isClientNameOK == true){
if(isTelephoneOK == true){
if(isCostOK == true){
double totalCost = selectedPizza.getPrice() + selectedPizzaSize.getPrice() + Double.valueOf(deliveryCost);
//everything is okey
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirm");
alert.setHeaderText("Total cost: " + totalCost);
alert.setContentText("Proceed with sale?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
int id = insertSale(timestamp, currentUser.getLogin(), selectedPizza.getID(),
selectedPizzaSize.getSize(), true, selectedPizza.getPrice() + selectedPizzaSize.getPrice());
insertDelivery(id, adress, clientName, telephone, Double.valueOf(deliveryCost));
infoTip.getInfoTip().setId("greenInfoTip");
infoTip.showTip((Button)event.getSource(), " Saved ");
} else {
// ... user chose CANCEL or closed the dialog
}
}else{ //cost not ok
infoTip.showTip(textFCost, "keep right format e.g. 4.35");
}
}else{ //telephone not ok
infoTip.showTip(textFTelephone, "max 20 characters, not empty");
}
}else{ //client name not ok
infoTip.showTip(textFClientName, "max 35 characters");
}
}else{ //adress not ok
infoTip.showTip(textFAdress, "max 50 characters, not empty");
}
}
}else{ //couldnt found selected pizza in pizzaList(which should not be possible)
ExceptionDialog exceptionDialog = new ExceptionDialog("Error when searching for selected pizza", new Exception());
exceptionDialog.showAndWait();
}
}else{ //pizza size not choosen
infoTip.showTip(comboPizzaSize, "select pizza size");
}
}else{ //pizza not choosen
infoTip.showTip(comboPizza, "select pizza");
}
}
I know now it has few major flaws:
method is doing too much and its too long,
it has too many conditional statements so it is easy to get lost,
unnecessary comments making code less readable.
repeated code,
possibly mixed levels of complexity.
testing it would be horrible.
something else??
How can I refactor it to make it clean and simple?
I'd take a slightly different approach to the other answer. I'd separate the validation from the other logic in the method. This means that you don't have to read lots of if statements to see the core logic of the method and if you want to change the validation you only need to update one statement in one place. eg for the first section, add a private method:
private PizzaSizeData getAndVerifySelectedPizza() {
if (comboPizza.getValue() == null) {
infoTip.showTip(comboPizza, "select pizza");
return null;
}
if (comboPizzaSize.getValue() == null) {
infoTip.showTip(comboPizzaSize, "select pizza size");
return null;
}
PizzaData selectedPizza = getPizzaData(comboPizza.getValue());
if (selectedPizza == null) {
ExceptionDialog exceptionDialog = new ExceptionDialog("Error when searching for selected pizza", new Exception());
exceptionDialog.showAndWait();
return null;
}
return getPizzaSizeData(comboPizzaSize.getValue());
}
You could return optionals instead of null but this illustrates the mechanism.
And then call the new method:
private void buttSellAction(ActionEvent event){
InfoTip infoTip = new InfoTip();
PizzaSizeData selectedPizzaSize = getAndVerifySelectedPizza();
if (selectedPizzaSize == null) {
return;
}
// Carry on with the method....
Putting validation at the start of a method with an early return statement is a common pattern so the multiple returns aren't going to confuse anyone and they allow each validation rule to be written separately.
you can use ladder if else in your code. like this
if(isAdressOK == true && isClientNameOK == true && isTelephoneOK == true && isCostOK == true){
double totalCost = selectedPizza.getPrice() + selectedPizzaSize.getPrice() + Double.valueOf(deliveryCost);
//everything is okey
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirm");
alert.setHeaderText("Total cost: " + totalCost);
alert.setContentText("Proceed with sale?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
int id = insertSale(timestamp, currentUser.getLogin(), selectedPizza.getID(),
selectedPizzaSize.getSize(), true, selectedPizza.getPrice() + selectedPizzaSize.getPrice());
insertDelivery(id, adress, clientName, telephone, Double.valueOf(deliveryCost));
infoTip.getInfoTip().setId("greenInfoTip");
infoTip.showTip((Button)event.getSource(), " Saved ");
} else {
// ... user chose CANCEL or closed the dialog
}
}else if(!isAdressOK == true){
infoTip.showTip(textFAdress, "max 50 characters, not empty");
}else if(!isClientNameOK == true){
infoTip.showTip(textFClientName, "max 35 characters");
}else if(!isTelephoneOK == true){
infoTip.showTip(textFTelephone, "max 20 characters, not empty");
}else{
infoTip.showTip(textFCost, "keep right format e.g. 4.35");
}
same for other if else condition.

stopping code at a certain point in a method

I'm making a program for school which inserts contacts into an array lists using JOptionPane/Dialog boxes for input/output.
The problem I'm having is with the Cancel and "X" buttons : when pressed by the user they crash the program.
I figured out using "return" I could stop the method, and that worked for the first dialog box but if information is entered and the user proceeds to the next Dialog box it crashes even though i'm using return again.
So basically what I want to do is if the user presses cancel or "X" to escape the current method it will do so without crashing and return to the main method to carry out other processes.
This code works for the first entry and exits the program successfully:
while(nameError)
{
surname = JOptionPane.showInputDialog(null, "Enter a Surname");
if(surname == null)
{
return;
}
else
{
if(!(surname.matches(NamesTest)))
{
JOptionPane.showMessageDialog(null,errorMsg);
}
else nameError = false;
temp[0] = surname;
}
}
but the next line of code in the method for the second Dialog box doesnt:
while(nameError1)
{
if(forename == null)
{
return;
}
else
{
forename = JOptionPane.showInputDialog(null, "Enter a Forename");
if(!(forename.matches(NamesTest)))
{
JOptionPane.showMessageDialog(null,errorMsg);
}
else nameError1 = false;
temp[1] = forename;
}
}
Something like this should do it:
import javax.swing.JOptionPane;
public class DialogExample {
public static void main(String[] args) {
new DialogExample().getNames();
}
private void getNames() {
String firstName = null;
String lastName = null;
while (firstName == null || firstName.length() == 0) {
firstName = getFirstName();
}
while (lastName == null || lastName.length() == 0) {
lastName = getLastName();
}
JOptionPane.showMessageDialog(null, "Hello " + firstName + " " + lastName);
}
private String getFirstName() {
String rtn = JOptionPane.showInputDialog(null, "Enter First Name");
if(rtn == null || rtn.length() == 0) {
JOptionPane.showMessageDialog(null, "Name cannot be empty");
}
return rtn;
}
private String getLastName() {
String rtn = JOptionPane.showInputDialog(null, "Enter Last Name");
if(rtn == null || rtn.length() == 0) {
JOptionPane.showMessageDialog(null, "Name cannot be empty");
}
return rtn;
}
}

How can I use instanceof Keyword Java

Is this the right way of validating using the instanceof keyword in java? Can I not use the || operator with this keyword? I am seeing errors in the line where I am writing the if condition to check if FieldName < = 0 and also when I am checking if it is equal to null or empty. Can anyone help me with the right way of writing the following piece of code. Thank you.
public static boolean validation(Object FieldName, String Name) {
if(FieldName instanceof Integer) {
if ((int) FieldName < = 0) {
errorCode = "EXCEPTION";
errorMsg = "Required field " + Name + " was not provided";
logger.debug(Name+ " is null ");
return true;
}
else {
}
}
else if (FieldName instanceof String) {
if(FieldName == null || FieldName.equals("")) {
errorCode = "EXCEPTION";
errorMsg = "Required field " +Name+" was not provided";
logger.debug(Name+" is null ");
return true;
}
//Here I check the fields for null or empty
}
Why not have two methods, one which takes an Integer and validates that, and one that validates Strings? Would that be simpler?
The line needs to be changed to
if (((int) FieldName) <= 0) {
when you don't put the parentheses around the cast completely the compiler will still believe it is an object and not an integer.
Try this. change the if and else body according to you
public static boolean validation(Object FieldName, String Name) {
if (FieldName instanceof Integer) {
if (((Integer)FieldName) <= 0) {
//an integer <= 0
return true;
} else {
// an integer >= 0
return true;
}
} else if (FieldName instanceof String) {
if (FieldName == null || FieldName.equals("")) {
// a String empty or null
return true;
}
else {
// a String non empty
return true;
}
}
return false;
}

Validating username part of email address

Consider an email id which is being provided in the starter class in the main method.
String emailId = "Hellooo_hell#gmail.com";
THE PROBLEM DESCRIPTION:
The overall length of the emailId should be >3 and <20.
The emailId must include "#" followed by a minimum of 1 and maximum of 2 "." characters.
The substring before "#" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
The first letter of the emailId must be in Upper Case.
If all the above conditions are valid it must display a success message or should display an appropriate ERROR message.
This is the code which does not work how I want it to.
public class EmailCheck {
String emailId;
public void setEmailId(String emailId){
this.emailId=emailId;
}
public String getEmailId(){
return emailId;
}
public static void main(String[] args) {
EmailCheck em = new EmailCheck();
em.setEmailId("Hell_ooo#gmail.com");
String email = em.getEmailId();
int length = email.length();
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
boolean flag4 = false;
boolean flag5 = false;
boolean flag6 = false;
boolean flag7 = false;
int count = 0;
int count2 = 0;
//Condition 1
if((length>3 && length<20)== true)
flag1 = true;
else
flag1 = false;
//Condition 2
for(int i=0;i<length;i++){
if(email.charAt(i)=='#'){
flag2 = true;
for(int j=i+1;j<length;j++){
if(email.charAt(j)=='.')
{
flag3 = true;
count=++count;
}
else
flag3 = false;
}
if(count<1 || count>2)
{
flag4 = false;
//System.out.println("Invalid position of special characters");
}
else
flag4 = true;
}
else
flag2 = false;
}
//Condition 3
if(email.matches("[a-zA-Z_]+#.*"))
flag5 = true;
else
flag5 = false;
//Condition4
if(Character.isUpperCase(email.charAt(0))==true)
flag6 = true;
else
flag6=false;
if(flag1==true && flag2==true && flag3==true && flag4==true && flag5==true &&flag6==true)
System.out.println("Email ID is valid");
else{
if(flag1==false)
System.out.println("Inavlid length of Email ID");
if(flag2==false||flag3==false||flag4==false)
System.out.println("Invalid Position of Special Characters");
if(flag5==false)
System.out.println("Invalid combination for username");
if(flag6==false)
System.out.println("Invalid case of first letter");
}
}
}
You can use the matches method from the String class
if(emailId.matches("[a-zA-Z_]+#.*")) {
// ok matches;
} else {
// does not match
}

How can I convert a JTextField that's returning null to a different string value?

I have a JTextField that I'm not always passing a value to, but it causes a NumberFormatException error to be thrown when the program runs if the person hasn't entered anything into the JTextField. I have some code below that I'm trying to convert a null response into a different String value. Why isn't it assigning stringInput as a String of "0"?
public int getOptionalDinners()
{
try
{
// get the input from the text field and determine if it's more than 0
String stringInput = " ";
stringInput = dinnerTextField.getText();
if (stringInput == null)
stringInput = "0";
int validAmount = Integer.parseInt(stringInput);
if (validAmount < 0)
throw new IllegalArgumentException();
dinnerQuantity = validAmount * 30;
}
catch (NumberFormatException error)
{
JOptionPane.showMessageDialog (null, "The number of dinners needs to be numeric.",
"Input Error", JOptionPane.ERROR_MESSAGE);
}
catch (IllegalArgumentException error)
{
JOptionPane.showMessageDialog (null, "The number of dinners needs to be higher than 0.",
"Input Error", JOptionPane.ERROR_MESSAGE);
}
return dinnerQuantity;
}
try
if (stringInput == null || stringInput.length() == 0) {
stringInput = "0";
}
You also need to check if it is 0 length.
Then assign the value back to the JTextField.
dinnerTextField.setText(stringInput);
you can change the below line:
if (stringInput == null)
to
if (stringInput == null || stringInput == "")

Categories

Resources