I have a number of fields where data needs to be input. This is a Hotel Reservation system so if the fields arent filled it must display that they are empty and cannot proceed without filling them. What I want to do is get the text from the fields but if they are blank it must either set all the fields text to something like "*Please fill in all fields" or show up a message.
I have some code which is not working because it cant get the text if there's nothing in the fields. The code looks like this:
this.Firstname = NameF.getText();
this.Lastname = NameL.getText();
this.Country = Countr.getText();
this.IDtype = IDTy.getText();
this.PassportNo = PassNo.getText();
this.IDNo = IDNumber.getText();
this.Addr1 = Add1.getText();
this.Addr2 = Add2.getText();
this.AreaCode = Integer.parseInt(Area.getText());
this.TelNo = Tel.getText();
this.CellNo = Cell.getText();
this.Email = Em.getText();
}
if (this.Firstname.equals("") || this.Lastname.equals("") || this.Country.equals("") || this.IDtype.equals("") || this.IDNo.equals("") || this.Addr1.equals("") || this.Addr2.equals("") || this.AreaCode == 0 || this.TelNo.equals("") || this.CellNo.equals("") || this.Email.equals("")) {
JOptionPane.showMessageDialog(null, "Please fill in all fields");
}
Not sure if I should ask this in another question but is there an easier way to make the if without so many || operators? Just like if this.Firstname,this.Lastname,etc.equals("")
You could do something like this.
public void validateFields () {
for (String field : getNonBlankFields()) {
if (field.equals("")) {
JOptionPane.showMessageDialog(null, "Please fill in all fields");
return;
}
}
}
Collection<String> nonBlankFields;
public Collection<String> getNonBlankFields () {
if (this.nonBlankFields != null) {
return this.nonBlankFields;
}
this.nonBlankFields = new ArrayList<String> ();
this.nonBlankFields.add(this.lastName);
// add all of the other fields
this.nonBlankFields.add(this.email);
return this.nonBlankFields;
}
You could do this by creating a function to do the checks for you in a loop;
public boolean isAnyEmpty(String... strArr){
for(String s : strArr){
if(s.equals("")) return true;
}
return false;
}
Then call it with
if(isAnyEmpty(this.Firstname, this.lastName, this.Country, /* rest of your strings */)){
//your code
}
This method makes use of varargs to let you treat the parameters as an array, without having to add in the additional code to explicitly create one.
You can create a method that will validate your Strings in varargs flavor:
public boolean validateString(String ... stringsToValidate) {
for (String validString : stringsToValidate) {
if (...) { //logic to validate your String: not empty, not null, etc
return false;
}
}
return true;
}
Then just call it like this:
//add all the strings that must be validated with rules defined in validateString
if (!validateString(NameF.getText(), NameL.getText(), Countr.getText(), ...) {
JOptionPane.showMessageDialog(null, "Please fill in all fields");
}
Related
below is my code that checks the incoming model and modifies the source accordingly, checking if its ALLCAPS or Firstcap. The problem I am having is when the model contains a symbol e.g. matchCase("I'm","apple"). This would return apple, when it's supposed to return Apple. On the other hand, If I use "Im", it modifies it correctly to "Apple". Is there a way i can modify it that would work. I tried to run a few methods but I keep getting stuck
public static String matchCase(String model, String source){
boolean o = true;
if(model.toUpperCase().equals(model)){
source = source.toUpperCase();
}
if(Character.isUpperCase(model.charAt(0))){
for(int i=1;i<model.length();i++){
if(Character.isLowerCase(model.charAt(i)) == false){
o = false;
}
}
// if(o == model.length()-1){
if(o == true){
String can = "";
for(int j=0;j<source.length();j++){
if(j==0){
can += Character.toUpperCase(source.charAt(j)); }
else{
can += source.charAt(j);
}
}
source = can;
// Character.toUpperCase(source.charAt(0));
}
}
return source;
}
}
I think your problem comes from the fact that
Character.isLowerCase('\'') // is false
You should change this test
if(Character.isLowerCase(model.charAt(i)) == false)
By
if(Character.isUpperCase(model.charAt(i)))
If you know your model is always going to be either uppercase or firstcap can't you do something like this:
public static String matchCase(String model, String source){
if(model.toUpperCase() == model)
return source.toUpperCase();
// capitalize the first letter of source and send back
return Character.toUpperCase(source.charAt(0)) + source.substring(1);
}
Say I have this section of code:
for(int i = 0; i < accounts.size(); i++) {
if(UserID.equals(accounts.get(i).getUserID())) {
if(accounts.contains(accounts.get(i))) {
if(UserPass.equals(accounts.get(i).getPassword())) {
System.out.println("True");
}
} else {
typePhrase("unrecognised userID: '" + UserID + "'");
}
} else {
typePhrase("unrecognised userID: '" + UserID + "'");
}
}
It goes through an arrayList filled with objects, that have an ID and a password. I get two inputs from the user, one is the userID, and the other is the password. What I want is for it to go through every possible object that is saved in that arrayList, and if it finds a match, print true into the console, the issue that I'm having is that if you type in something wrong, it prints an message that it is unrecognised for every object in the arrayList. It also prints the message for every object that there is in the arrayList -1 if you type one in right. What do you suggest I do?
User class:
public class User {
String userID;
String password;
public User(String ID, String Pass) {
userID = ID;
password = Pass;
}
public String getUserID() {
return userID;
}
public String getPassword() {
return password;
}
}
EDIT:
ArrayList<User> accounts = new ArrayList<User>();
You should implement equals method in the User class:
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (!getUserID().equals(user.getUserID())) return false;
return getPassword().equals(user.getPassword());
}
Then you can create a new User with the typed information and just check if the list contains this User:
User user = new User("typedUserId", "typedPassword");
System.out.println(accounts.contains(user));
This is a mistake I see newer programmers often make. You're searching through a list to see if any element meets some condition (e.g. ID and password match). If no element meets the condition, you do something that indicates an error.
But you can't tell if there's an error until you've gone through every element of the list. Therefore, any error message has to occur after the loop is completely done, right? Not in the middle of the loop. But you've put your "unrecognised" message in the middle of the loop. That can't work.
There are several common idioms to solve this, but here's a simple one:
boolean found = false;
for (whatever-your-loop-should-look-like) {
if (the-current-element-meets-the-condition) {
found = true;
break;
}
}
if (!found) {
whatever-action-you-take-when-it-isn't-found;
}
Remove this check... It makes no sense while you loop over those objects to check if the current object is inside the list of objects it came from.
if(accounts.contains(accounts.get(i))) {
Without this, your code prints True (but continues to check the rest of the list) when the userID and password match. Otherwise, the other message is printed. If you want to stop the loop when you print True, put break there.
To address the problem, though, User.equals() is not implemented, so the default way to compare objects is used (via the hashcode method).
You should implement that to compare equality of userID and password.
Not sure if implementing equals() is a wise choice here. However, isn't that what you are trying to do as simple as:
boolean found = false;
for (User u : accounts) {
if (userId.equals(u.getUserId()) && userPass.equals(u.getPassword()) {
found = true;
break;
}
}
You may even use stream API if you are in Java 8+
accounts.stream().anyMatch(u -> userId.equals(u.getUserId())
&& userPass.equals(u.getPassword());
Instead of printing true or not found, you can keep a boolean variable with whether you have found a match or not.
boolean found = false
for each value in the array
if it's a match set found to true
if it's not a match do nothing, i.e. continue to next position
if (found) print "true" else print "not found"
You can also break out of loop if you found a match, no need to keep checking for more matches.
boolean found = true
for each value in the array
if it's a match set found to true and break out of loop
if it's not a match do nothing, i.e. continue to next position
if (found) print "true" else print "not found"
Even better, you can move the code to a method that returns boolean and get rid of the variable.
boolean isThereAMatch() {
for each value in the array
if it's a match set return true
if it's not a match do nothing, i.e. continue to next position
return false
}
And you can call it to check what to print.
if (isThereAMatch()) print "true" else print "not found"
You're struggling with whether to use contains() of List or to use a simple for loop. It can be done both ways, below is the code sample for both. For using the contains you'll have to add an equals() overridden method to User.
From the List.contains() documentation
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
With For Loop
import java.util.*;
public class TestMain {
public static void main (String[] args) {
List<User> accounts = new ArrayList<User>();
User user1 = new User("test", "test");
User user2 = new User("test1", "test1");
accounts.add(user1);
accounts.add(user2);
String userId = "test";
String userPass = "test1";
boolean matchFound = false;
for(User account : accounts) {
if(userId.equals(account.getUserID()) && userPass.equals(account.getPassword())) {
System.out.println("True");
matchFound = true;
}
}
if(!matchFound) {
System.err.println("unrecognised userID: '" + userId + "'");
}
}
}
class User {
String userID;
String password;
public User(String ID, String Pass) {
userID = ID;
password = Pass;
}
public String getUserID() {
return userID;
}
public String getPassword() {
return password;
}
}
With contains() and equals()
import java.util.*;
public class TestMain2 {
public static void main (String[] args) {
List<User> accounts = new ArrayList<User>();
User user1 = new User("test", "test");
User user2 = new User("test1", "test1");
accounts.add(user1);
accounts.add(user2);
String userId = "test1";
String userPass = "test1";
boolean matchFound = accounts.contains(new User(userId, userPass));
if(!matchFound) {
System.err.println("unrecognised userID: '" + userId + "'");
} else {
System.out.println("True");
}
}
}
class User {
String userID;
String password;
public User(String ID, String Pass) {
userID = ID;
password = Pass;
}
public String getUserID() {
return userID;
}
public String getPassword() {
return password;
}
#Override
public boolean equals(Object user) {
boolean isEqual = false;
if(user != null && user instanceof User) {
User userType = (User)user;
boolean userIdMatched = (userID == null) ? userType.getUserID() == null : userID.equals(userType.getUserID());
boolean passwordMatched = (password == null) ? userType.getPassword() == null : password.equals(userType.getPassword());
isEqual = userIdMatched && passwordMatched;
}
return isEqual;
}
}
I am trying to validate user input into text boxes. I am checking whether the text box is populated or not and if it's not I need to alert the user to which text box isn't populated. My problem is that I need a way of returning which text box / variable is empty. I am aware I will need to pass 2 values in, one being the content of the text box and the other, an identifier of the text box.
Currently I have this (found on StackOverflow) which checks if each variable in the array is populated.
public boolean areAllNotEmpty(String... text){
for(String s : text) {
if(s == null || "".equals(s)) {
return false;
}
}
return true;
}
I would like it to also return something like this (commented):
public boolean areAllNotEmpty(String... text){
for(String s : text) {
if(s == null || "".equals(s)) {
// return textbox name / value OR show alert box with "Forename missing" etc
return false;
}
}
return true;
}
I implemented this method before on a C# project but it requires passing in one text box at a time with multiple method calls which I'm guessing isn't great.
public static bool IsFieldNull(TextBox currentText, string type)
{
bool allOk = false;
if (currentText.Text == "")
{
MessageBox.Show("Error - '" + type + "' field cannot be left blank, please enter some data in this field");
currentText.Focus();
return allOk;
}
else
{
allOk = true;
return allOk;
}
This is how it is called in C#.
Validation.IsFieldNull(txtBoxFixtureDate, "Fixture Date") && Validation.IsFieldNull(txtBoxTime, "Time")
If any of that doesn't make sense, let me know.
Thanks for any help.
You could pass the components to the method and return ones that are empty like this:
public List<JTextField> getEmptyFields(JTextField... textFields) {
List<JTextField> emptyFields = new ArrayList<JTextField>();
for (JTextField field : textFields) {
if (field.getText().isEmpty()) {
emptyFields.add(field);
}
}
return emptyFields;
}
Then you can just check the size() of the returned list to determine if there was an empty field and deal with them accordingly.
It's not pretty useful to validate when a submit button is pressed, it's better to validate when the error is happening. You may consider using InputVerifier . Then you know when it's in valid state or not. Apart from that if you are using java7 or above you could take a look to JLayer to decorate components which are not in valid state. See here for more examples Decorate components with JLayer.
I am trying to validate some input from a Swing form by checking for null values. However the checkFirstName method is always returning true. So for example if i leave the firstname blank on the form it will return true even though the field is null.
Here is my two methods, the first one is fired when the user clicks the save button.
public void saveNewCustomer() throws SQLException, ClassNotFoundException {
boolean dbOK = false;//boolean to check if data input is not null
System.out.println(dbOK);
String firstName = txtNCustomerFirstName.getText();
String lastName = txtNCustomerLastName.getText();
if (checkFirstName(firstName)) {
dbOK = true;
} else {
lblNCustFirstNameError.setText("First Name Must be Entered");
dbOK = false;
}
System.out.println(dbOK);
if (dbOK) {
dbConnector.insertSignup(firstName, lastName);
System.out.println("Success");
} else {
System.out.println("Error");
}
}
public boolean checkFirstName(String firstName) {
boolean allOK = false;
System.out.println(allOK);
if (firstName != null) {
allOK = true;
} else {
allOK = false;
}
return allOK;
}
Have i done something wrong cause this to me should be return false cause the firstname field is null.
The String will never be null, the String will be empty. Check firstName.isEmpty(). Still I suggest you keep the check for null too:
public boolean checkFirstName(String firstName) {
boolean allOK = false;
System.out.println(allOK);
if (firstName != null && !firstName.isEmpty()) {
allOK = true;
} else {
allOK = false;
}
return allOK;
}
EDIT: as pointed out by Windle you probably would like to check if the String has at least one non-whitespace:
if (firstName != null && !firstName.trim().isEmpty())
Also you may perform more complex verification - for instance if you want to make sure there are no whitespaces in the username after you trim it.
So for example if i leave the firstname blank on the form
You are just checking for null, you need to do empty ("") String check also.
It should be something like:
if (firstName != null && !"".equals(firstName.trim()) {
The txtNCustomerFirstName.getText method is returning an empty string. You might change your checkFirstName method's if statement to check for an empty string:
if (firstName != null && !firstName.isEmpty()) {
If you don't have Java 6+, you can use firstName.length() > 0 instead of isEmpty.
As far as I'm aware, the getText() method you're calling in the saveNewCustomer() will return an empty string rather than null.
So for example if i leave the firstname blank on the form it will
return true even though the field is null.
This is where your reasoning is wrong. When you leave a text field blank, getText() returns an empty string i.e. "" which is not null. You should check for emptiness instead of null.
if (!firstName.isEmpty()) { ... }
If firstName may also be null (e.g. when it comes from another source), you should check that beforehand:
if (firstName != null && !firstName.isEmpty()) { ... }
As other answers have suggested do a null check with an empty string check. I'd say trim the leading and trailing whitespaces also before doing an empty check because in reality you want to avoid such situation.
if (firstName != null && !firstName.trim().isEmpty()) { ... }
For example:
getBooks(author, title)
If allowing author to be null, would return all books with specific title
If allowing title to be null, would return all books for the specific author
If allowing both to be null, would return all books regardless of title or author
To eliminate this, have the following functions:
getBooks(author)
getBooks(title)
getBooks(author, title)
getBooks()
In the new functions, there might be redundant codes or if we group those redundant codes into a function, we will still get into a function having null parameters. What's a better way to handle this - no redundant code and no null parameters?
Don't overload so much:
getBooksByAuthor(author)
getBooksByTitle(title)
getBooksByAuthorAndTitle(author, title)
getBooks()
Note that this will not reduce code reuse: These methods could reuse/share whatever code they needed to in their implementations
You could use a constant to denote what type of search to do, and check to see if a param was passed (very untested and error checked):
public static final int R_AUTH = 1;
public static final int R_BOOK = 2;
public static final int R_ALL = 3;
public bookSearch( int searchType, String... search )
{
switch( searchType )
{
case R_AUTH:
// search based off of (String)search[0].stringValue();
break;
case R_ALL:
// load all
break;
}
}
bookSearch(R_ALL);
bookSearch(R_AUTH, "Poe");
Assuming that author and title are Strings you can do the following:
public List getBooks(String params ...) {
if (params.length == 0) { //search
//do search all books regardless of title or author
} else if (params.length == 2 && "cte_author".equals(params[1])) {
//do search by author
} else if (params.length == 2 && "cte_title".equals(params[1])) {
//do search by title
} else if (params.length == 2){
//do search by title and book
} else {
//throw exception
}
}
So you can use this method as following:
getBooks();
getBooks("Gabriel Garcia Marquez", "cte_author");
getBooks("Cien anios de soledad", "cte_title");
getBooks("Gabriel Garcia Marquez","Cien anios de soledad");
Try this approach:
getAllBooks() {return getBooks("", "");}
getBooksByAuthor(author) {return getBooks(author, "");}
getBooksByTitle(title) {return getBooks("", title);}
getBooksByAuthorAndTitle(author, title)
{
if(author.equals("") && title.equals(""))
{
return //your book list
}
else if(author.equals(""))
{
return //a list of books with the given title
}
else if(title.equals(""))
{
return //a list of books with given author
}
else
{
return //a list of books with the given title and author
}
}
Edit:
Updated to circumvent ambiguity.