Validating a function in a database - java

I'm not sure how to validate this so that if an id value isnt found i can say that the ID value doesn't exist. i have a GUI function with a database in which you enter a id (attribute) of someone and it returns their other information (name, surname, etc) but when an id is not found my program crashes and im not quite sure how to make so that i can use a JOption pane when an id is not found.
int id = Integer.parseInt(jTextField15.getText());
Person updatePerson = new Person();
for (Person person : personList)
{
if (person.getPersonid() == id)
{
updatePerson = person;
}
}
jTextField11.setText(updatePerson.getFirstname());
jTextField17.setText(updatePerson.getSurname());
jTextField12.setText(updatePerson.getPersontype());
jTextField16.setText(updatePerson.getGender());
jSpinner5.setValue(updatePerson.getDateofbirth());
The program seems to work but i am getting an exception in thread message after it cant find the id:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: illegal value
any help to explain what this is and how to fix it as well as being able print a message to the user would be very appreciated

I am assuming you mean the following:
what should I do in my GUI when I look up an element and it is not found.
There are 2 approaches you can take:
1: leave out the elements. This works well (usually) for html and other generated user interfaces. After your loop you check if the updatePerson == null, if so, you skip generating the html elements (or text fields, etc)
2: for GUI's you generally use a default value. This can be done in one of 2 ways: you use default values for each field, or you create a dummy object.
int id = Integer.parseInt(jTextField15.getText());
Person updatePerson = null;
for (Person person : personList)
{
if (person.getPersonid() == id)
{
updatePerson = person;
break; // with break: get first found, without break: get last found.
// this depends on whether it is possible to have a person show up more than once.
}
}
if (person == null) {
jTextField11.setText("");
jTextField11.setVisible(false); // setting fields to empty, in case logic
jTextField17.setText(""); // is using them or if someone
jTextField17.setVisible(false); // sets visible true before setting text
jTextField12.setText(""); // as you don't want to output wrong data
jTextField12.setVisible(false); // even for a flicker of a second
jTextField16.setText("");
jTextField16.setVisible(false);
jSpinner5.setValue(SOME_GLOBAL_DEFAULT_DATE); // ie. 0 or 1970-01-01
jSpinner5.setVisible(false);
} else {
jTextField11.setText(updatePerson.getFirstname());
jTextField17.setText(updatePerson.getSurname());
jTextField12.setText(updatePerson.getPersontype());
jTextField16.setText(updatePerson.getGender());
jSpinner5.setValue(updatePerson.getDateofbirth());
}
or you can do (leaving the fields, but empty)
int id = Integer.parseInt(jTextField15.getText());
Person updatePerson = new Person(); // default constructor initializes with empty of default values
for (Person person : personList)
{
if (person.getPersonid() == id)
{
updatePerson = person;
break; // with break: get first found, without break: get last found.
// this depends on whether it is possible to have a person show up more than once.
}
}
jTextField11.setText(updatePerson.getFirstname());
jTextField17.setText(updatePerson.getSurname());
jTextField12.setText(updatePerson.getPersontype());
jTextField16.setText(updatePerson.getGender());
jSpinner5.setValue(updatePerson.getDateofbirth());
While writing this I realise I would end up doing a third approach which is related to the first:
if (updatePerson == null) {
panelContainingFields.setVisible(false);
} else {
jTextField11.setText(updatePerson.getFirstname());
jTextField17.setText(updatePerson.getSurname());
jTextField12.setText(updatePerson.getPersontype());
jTextField16.setText(updatePerson.getGender());
jSpinner5.setValue(updatePerson.getDateofbirth());
panelContainingFields.setVisible(true);
}
Simply put all the fields you use in a panel, and hide the panel when there's no elements.

Related

Checking if a HashMap is empty without causing NullPointerException / IndexOutOfBoundsException?

So am doing a mail server kind of program for my java course, (I would call myself a beginner in Java) and while I have completed all the required parts, there are some problems with the program that while the assignment doesn't require it, I would like to know why this is behaving the way and how to fix it. So to summarize it I have two methods that check how many mail items a specific user has and another one that returns the mail item that is first in the users mailbox, (by LIFO rule).
So while if a user both A.Has a mailbox and B.Has at least 1 mail in said mailbox there isn't a problem, this doesn't really work when a and/or b isn't true. And that is what I tried to fix. I thought it would be as simple as checking both if the mailbox.containsKey(who)==false and/or mailbox.get(who).get(0) == null would be enough but when I do this i get java.lang.IndexOutOfBoundsException: Index: 0, Size: 0.
I've tried multiple types of either checking if it's ==true/false null etc.. I've tried to just throw the exception all together but nothing seems to work and while maybe throwing the exception could work in some way I would want to solve it in another way as the throw command seems a bit lazy
Here is my method in which I check both A and B:
private boolean errorHandling(String who){
if (mailbox.containsKey(who)==false || mailbox.get(who).get(0) == null ){
return true;
}
else{
return false;
}
}
and this method is utilized by these two methods:
public MailItem getNextMailItem(String who)
{
if (!errorHandling(who) ){
MailItem item2 = mailbox.get(who).get(0);
mailbox.get(who).remove(0);
return item2;
} else{
System.out.println("that user dosent have a mailbox");
return null;
}
}
public int howManyMailItems(String who)
{
if (!errorHandling(who) ){ //To check if user has a mailbox
return mailbox.get(who).size();
}
else{
System.out.println("that user dosent have a mailbox");
return 0;
}
}
I am not sure if you need more of my code to help me or not. Tell me if that is the case but to clarify, the "mailbox" is the hashmap and the who parameter is the person you want to check his or her mailbox. Thank you.
There are couple of problems in our code which i listed below
First Problem
The if condition is wrong and which will be true even if map doesn't contain key
if (mailbox.containsKey(who)==false || mailbox.get(who).get(0) == null)
// mailbox.containsKey(who) will return false if map doesn't contain key
// then false==false ---> always true
So you are returning true even key is not present in map, And there is not necessity of errorHandling method. you can just use containsKey
if (containsKey(who) ){ // if key exists then proceed
MailItem item2 = mailbox.get(who).get(0);
mailbox.get(who).remove(0);
return item2; }
else{ // else don't proceed
System.out.println("that user dosent have a mailbox");
return null;
}
You can even avoid this `if condition by using getOrDefault
default V getOrDefault(Object key, V defaultValue)
Second Problem
Second part of if condition is wrong mailbox.get(who).get(0) == null you might have empty list for that key, so you can refactor your code as below
List<MailItem> listItem = mailbox.get(who, new ArraysList<>()); //get list if key exists or else get empty list
if(!listItems.isEmpty()) {
return listItems.remove(0); //if list has items delete at index 0
}
else{
System.out.println("that user dosent have a mailbox");
return null;
}

Recursively counting unique objects inside nested vectors

I would like to count the number of unique objects which are inside a particular Vector. For example, I have a class Person which has Vector<Person> family. I 'm trying to find a way to count the length of the extended family. There could be relations between people such as:-
Mike is related to Pete;
Mike is related to John;
John is related to Amy;
Mike would have an extended family of 4 (which includes himself).
I figured the only way to do this is with recursion and I have something like this so far.
public int getExtendedFamily(Person person) {
// Add the current person if he/she does not exist
if (!(lineage.contains(person))) {
lineage.add(person);
// If the person has no direct family
if (person.getFamily().size() == 0)
return lineage.size();
else {
// Otherwise iterate through the family members
for (Person familyMember : person.getFamily()) {
return lineage.size() + getExtendedFamily(familyMember);
}
}
} else {
// Person already exists...
return lineage.size();
}
return 0;
}
I've created a new vector lineage to keep track of the unique people I come across.
Obviously I know I'm some way off with this code as my lineage.size() isn't right. I just can't get my head around how to structure the recursion, Any guide would be appreciated. Even if it's just pseudocode!
Kind Regards,
Ben
updated code, appears to work
public int getExtendedFamily(Person person) {
// If the person exists just return counter,
//and go back up the call stack;
if ((lineage.contains(person))) {
return counter;
} else {
// Otherwise add the person to the lineage data structure
// and continue
lineage.add(person);
// Loop through current persons family
for (Person family_member_ : person.getFamily()) {
// If the current family member index is not in the lineage
// then increase the counter and recursively call getExtendedFamily,
// to count that persons unique family members.
if (!lineage.contains(family_member_)) {
counter++;
getExtendedFamily(family_member_);
};
}
}
return counter;
}
It would probably just be the vector's size plus one, assuming the relationships are all saved.
If you are getting into generations, where the descendants are not reported in the grandparent, the recursive way to do it would be to return the size of the vector and return if there are no children.
If there is no requirements that the relationships are fully saved, pass a set to the recursive function and save to the set. Return when the vector is 0.

Second record doesnt get stored in arraylist

I have an arraylist which the records are stored as objects.
In a different form i allow the user to enter an id and retrieve the data of that record with the corresponding id.
My problem is , i can only retrieve one record , meaning only the first record which i store in the arraylist.
If i type in a second record and if try to search the record using the id , i get the message "invalid id", its the message which i assigned to make sure that users won't enter invalid ids.
Here is the code which i used to store the object in to the arraylist:-
patient_class patients=new patient_class(firstname,lastname,initials,gender,birthday,birthmonth,birthyear,contactnumber,address,bloodgroup,patientid);
patientlist.add(patients);
Here is my code to check whether if the arraylist contains the id.
public boolean checkrecord(ArrayList<patient_class>patients,String search)
{
for(patient_class patient : patients)
{
if(patient.getid().contains(search))
{
return true;
}
}
return false;
}
if the it is true i have the created a separate constructor to find the record for the give id.
Here is the code for that :-
public patient_class searchrecord(ArrayList<patient_class> patients, String search)
{
for(patient_class patient: patients) //used enhanced for loop
if(patient.getid().equals(search))
{
return patient;
}
else
{
return null;
}
return null;
}
Why can i only enter one record but not 2 records in to the arraylist ? My program display "succussfuly registered" when i enter the second record and click register, but i cant search that record , but i can delete the record using another method i made.
What am doing wrong ?
This is the problem:
for(patient_class patient: patients) //used enhanced for loop
if(patient.getid().equals(search))
{
return patient;
}
else
{
return null;
}
return null;
Due to your else block, you're returning null if the first patient doesn't match the patient you're looking for, instead of looking for other matches. You should get rid of the else block. I'd also add braces to make the control flow clearer:
for (patient_class patient : patients) {
if (patient.getid().equals(search)) {
return patient;
}
}
// Only return null if we've checked *all* patients
return null;
Additionally, I'd strongly advise you to start following Java naming conventions, renaming patient_class to Patient and the getid method to getId:
for (Patient patient : patients) {
if (patient.getId().equals(search)) {
return patient;
}
}
return null;

Searching an ArrayList

I currently have 3 classes, a main class containing a GUI, in which i'm calling this method, a customer class containing the data, and a customerList class which gathers the data from the customer class, puts it into an array list, and also contains the search arraylist method.
I'm trying to implement a search method which can be called from my main class on an action event handler. I'm having a few problems though.
Whenever I run the method, the " System.out.println(customer.returnFamilyName());" line always displays the first familyname in my arraylist.
Don't hesitate to ask for more information, I'm not sure how well i've explained this.
Here is my method:
public void searchCustomer(String familyName) {
int index = 0;
boolean found = false;
customer customer;
while(index < CustomerList.size() && !found) {
customer = CustomerList.get(index);
if(customer.returnFamilyName().equalsIgnoreCase(familyName)) {
found = true;
break;
}
if(found == true) {
;
}
System.out.println(customer.returnFamilyName());
index++;
return;
}
}
It's not clear from your question what the intended behaivor actually is. Besides that, what is this ?
if (found == true);
Presumably you meant :
if (found) {
System.out.println...
}
But what if the same last name occurs twice in your list? Also why aren't using a Map instead of a List? Lookup will go from being O(n) to O(1)
Drop the ; in if (found == true); because that reads as: if this condition is true, do notihng and use braces always:
if (found == true) {
System.out.println(customer.returnFamilyName());
}
Also, include the increment inside the while loop, otherwise you are not really iterating anything.
This code seems to work because your first element happens to coincide with the searched element, try with a different one and you'll end up in a infinite loop.
Try with a version like this:
public void searchCustomer( String familyName ) {
for ( customer current : CustomerList ) {
if ( current.returnFamilyName().equalsIgnoreCase( familyName )) {
System.out.println( current.returnFamilyName() );
break;
}
}
}
Some additional remarks:
In Java clases should start with uppercase, so the class name should be declared as Customer instead of customer and variables start with lowercase, hence CustomerList should be customerList. Methods may avoid the return part and be named with a get
Also, search methods should better return the found value instead of printing it, so your final version could look like this:
public Customer searchCustomer( String familyName ) {
for ( Customer current : customerList ) {
if ( current.getFamilyName().equalsIgnoreCase( familyName ) ) {
return current;
}
}
return null;
}
You never increment index.
The code should be:
public void searchCustomer(String familyName) {
for (customer customer : CustomerList) {
if (customer.returnFamilyName().equalsIgnoreCase(familyName)) {
System.out.println(customer.returnFamilyName());
break;
}
}
}
Also, the 'customer' class should be called 'Customer' as class names should start with a capital, 'returnFamilyName' should be 'getFamilyName' as accessor methods by convention are named 'get' + the field name and 'CustomerList' should be 'customerList' as field names are supposed to start with a lowercase letter.
I would suggest try this:
System.out.println(customer.returnFamilyName());
index++;
if(found == true) { return;}
Don't forget to increment the while loop or it has the potential to run indefinitely.
You can elect to use what is known as an "enhanced for-loop", which allows you to eschew the need to increment values over CustomerList entirely. You have an object customer, so we can use that as follows:
for (customer cus: CustomerList) {
if(cus.returnFamilyName().equalsIgnoreCase(familyName)) {
System.out.println(cus.returnFamilyName());
return;
}
}
If you elect to stick with your original code (which is fine), then observe the changes in your code below.
while(index < CustomerList.size()) {
customer = CustomerList.get(index);
if (customer.returnFamilyName().equalsIgnoreCase(familyName)) {
System.out.println(customer.returnFamilyName());
break;
} else {
index++;
}
}

Using a for each loop to find two elements in an array list

I need help writing a for each loop which searches through an array list called peoplelist of type people. The loop needs to search for the values String postcode and String name in the array. It then needs to return their ID if it is found, and null if it is not. Any sort of help would be great!
If the class People is written like a Java bean (i.e. with standard getter methods), something like this would do the job:
for (People person : peopleList) {
if (person.getName().equals(name) && person.getPostcode().equals(postCode))
return person.getId();
}
return null;
If a person's name or postcode can be null, you may want to flip the equals calls to avoid null pointer exceptions (e.g. name.equals(person.getName()) instead of person.getName().equals(name)).
Btw Person would be a better name.
Need to make a lot of assumptions about your classes, but something like this should suffice:
for (People person : peoplelist) {
if (person.getPostCode().equals(postcode) && person.getName().equals(name)) {
return person.getId();
}
}
// deal with not being found here - throw exception perhaps?
With “two elements”, do you mean “two attributes of some class”? If so, something along these lines would do:
String id = null;
for(People p : peoplelist) {
if(somePostcode.equals(p.postcode) && someName.equals(p.name)) {
id = p.id;
break; // no need to continue iterating, since result has been found
}
}
// result “id” is still null if the person was not found
//In case multiple persons match :)
List<String> result = new LinkedList<String>();
for (People person : peopleList) {
if (person.getName().equals(name) && person.getPostcode().equals(postCode))
result.add(person.getId());
}
if(result.isEmpty()){
return null;
}else{
return result;
}
People foundPerson;
for (People eachPeople : peoplelist )
{
if (Integer.valueOf(eachPeople.getID()) == 10054
&& "Jimmy".equals(eachPeople.getName()))
{
foundPerson= eachPeople;
break;
}
}
Assuming you have a Person bean, then if you want to retrieve all instances of Person whose postcode and name match some values, you may do something like this:
public List<Person> searchFirst(List<Person> persons, String postcode, String name) {
List<Person> matchingPersons = new ArrayList<Person>();
for (Person person : persons) {
if (person.getPostcode().equals(postcode) && person.getName().equals(name))
matchingPersons.add(person);
}
return matchingPersons;
}
Next time, you may want to show us your code, so we can help you in understanding what you're doing wrong :)

Categories