How to debug a JOption error message in Java? - java

I am doing a school management system project, everything is good except when I try to click the save button it returns the JOption error message that phone must be integer although it is already. I must say I have a similar form for teacher registration and that one works. How can it be?
private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {
try{
int day = Integer.valueOf((String)jComboBoxDay.getSelectedItem());
int month = Integer.valueOf((String)jComboBoxMonth.getSelectedItem());
int year = Integer.valueOf((String)jComboBoxYear.getSelectedItem());
String birthDate = ""+day+month+year;
String firstName = jTextFieldFirstName.getText();
String lastName = jTextFieldLastName.getText();
String address = jTextFieldAddress.getText();
String email = jTextFieldEmail.getText();
int phoneNumber = Integer.parseInt((jTextFieldPhoneNumber).getText());
String gender = (String)jComboBoxGender.getSelectedItem();
String religion = jTextFieldReligion.getText();
String contactTeacher =jTextFieldContactTeacher.getText();
int contactPhoneNumber = Integer.parseInt((jTextFieldContactPhoneNumber).getText());
int momID = Integer.parseInt((jTextFieldMotherID).getText());
int fatherID = Integer.parseInt((jTextFieldFatherID).getText());
Reset();
Students student = new Students(birthDate,firstName,lastName,address, email,phoneNumber,gender,religion,contactTeacher,contactPhoneNumber,momID,fatherID);
studentsControl.createStudents(student);
loadTable();
}
catch (NumberFormatException exception)
{
JOptionPane.showMessageDialog(null,"Phone must be an integer ","Error",JOptionPane.ERROR_MESSAGE);
jTextFieldPhoneNumber.setText("");
}
}

You're getting the month description from jComboBoxMonth object.
Try getting the index instead by calling getSelectedItem method and adding 1.

Related

Java remove button

This is how the GUI looks
I have a GUI program that stores user's details (such as salary, fname, lname, date) into an arraylist using an add button. After the user presses add, the user presses list to output all the information into a panel.
My full code is below.
public class EmploymentRecords extends javax.swing.JFrame {
ArrayList <Data> Output = new ArrayList <Data>();
Add button:
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
Data d;
String id, firstName, lastName, salary, startDate;
id = txtID.getText();
firstName = txtFName.getText();
lastName = txtLName.getText();
salary = txtSalary.getText();
startDate = txtDate.getText();
d = new Data(id, firstName, lastName, salary, startDate);
Output.add(d);
}
List Button:
private void btnListActionPerformed(java.awt.event.ActionEvent evt) {
String print = "";
for (int i=0; i<=Output.size()-1; i++)
{
print = print + "ID #:" + Output.get(i).id + ", "
+ Output.get(i).firstName + " "
+ Output.get(i).lastName + ", "
+ "$" + Output.get(i).salary + ", "
+ Output.get(i).startDate + "\n ";
}
pnlOutput.setText(print);
}
Remove Button:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
int index;
String id = txtID.getText();
boolean idCheck = Output.contains(id);
if (idCheck == true){
index = Output.indexOf(id);
Output.remove(index);
}
else {
lblError.setText("Employee not found. Please try again.");
}
Data Class:
class Data {
String id, firstName, lastName, salary, startDate;
Data (String _id, String _firstName, String _lastName, String _salary, String _startDate) {
id = _id;
firstName = _firstName;
lastName = _lastName;
salary = _salary;
startDate = _startDate;
}
}
I have everything working such as the list and add button, but my problem is with the Remove button: The user has a button to remove a single employees data from the arraylist based on only writing the the ID in the text area, which also removes all the information outputted to the user in the panel. My code above for the remove button doesnt work and when I press remove, nothing happens and the data stays there in the output panel.
Id really appreciate any help I get on this remove button
This solution uses the streaming API:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
int index;
String id = txtID.getText();
List<Data> elementsWithId = Output.stream() // Use the streaming API on Output
.filter(data -> data.id.equals(id)) // filter out the element(s) with matching id
.collect(Collectors.toList()); // put the findings into a new list
boolean idCheck = (elementsWithId.size() > 0);
if (idCheck == true){
for (Data data: elementsWithId) {
Output.remove(data);
}
}
else {
lblError.setText("Employee not found. Please try again.");
}
// Pass the event on to the list functionality:
btnListActionPerformed(evt);
}
So, the real "magic" happens in the commented lines. You'll search the whole Output list for elements with the given ID and create a new list containing the matches only. (I understood, there should be one at most, but you never know...)
The rest is quite the same as you had it before, just that we're working with the result list here.
Please note, that there are serveral approaches to your problem and this is just one the quick and easy ones. There are more elaborate ones for sure.

NullPointerException when using .size() in an Arraylist class

currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main

Saving the values of a string to another class and retrieving it

I am currently trying to save the values of a string to another class file in JAVA called Memory.JAVA. The reason why I am doing this is because variables are not saved outside the Try - Catch Blocks. Therefore I initiate the class in the try catch block by using this code:
Memory mem = new Memory();
And then when I want to save a string, I use the following:
mem.brother1ID = "Whatever";
The reason why I am not creating it as a new String is because in the Memory class, I have already initiated this string. To test that this has been saved, I have used System.out.println to print out the result which in this case was "Whatever" but when I try to get the same result printed out in the same class, I get the result "null". Does anyone have any suggestions regarding my issue? Please feel free to comment below. Thanks!
UPDATE:
Some code posted below:
private void searchFieldKeyReleased(java.awt.event.KeyEvent evt) {
try {
Memory mem = new Memory();
String sql = "select * from userInfo where firstName= ? OR lastname = ?";
pst=conn.prepareStatement(sql);
pst.setString(1, searchField.getText());
pst.setString(2, searchField.getText());
rs=pst.executeQuery();
if(rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String placeOfResidence = rs.getString("placeOfResidence");
String employmentStatus = rs.getString("employmentStatus");
String currentEmployer = rs.getString("currentEmployer");
String taxStatus = rs.getString("taxStatus");
String dateOfBirth = rs.getString("dateOfBirth");
String mother = rs.getString("mother");
String father = rs.getString("father");
String brother1 = rs.getString("brother1");
String brother2 = rs.getString("brother2");
String brother3 = rs.getString("brother3");
String brother4 = rs.getString("brother4");
String brother5 = rs.getString("brother5");
String sister1 = rs.getString("sister1");
String sister2 = rs.getString("sister2");
String sister3 = rs.getString("sister3");
String sister4 = rs.getString("sister4");
String sister5 = rs.getString("sister5");
mem.brother1ID = rs.getString("brother1ID");
mem.brother2ID = rs.getString("brother2ID");
mem.brother3ID = rs.getString("brother3ID");
mem.brother4ID = rs.getString("brother4ID");
mem.brother5ID = rs.getString("brother5ID");
mem.sister1ID = rs.getString("sister1ID");
mem.sister2ID = rs.getString("sister2ID");
mem.sister3ID = rs.getString("sister3ID");
mem.sister4ID = rs.getString("sister4ID");
mem.sister5ID = rs.getString("sister5ID");
mem.fatherID = rs.getString("fatherID");
mem.motherID = rs.getString("motherID");
System.out.println(mem.brother1ID);
System.out.println(firstName + " " + lastName);
firstNameField.setText(firstName);
lastNameField.setText(lastName);
placeOfResidenceField.setText(placeOfResidence);
employmentStatusField.setText(employmentStatus);
currentEmployerField.setText(currentEmployer);
taxStatusField.setText(taxStatus);
dateOfBirthField.setText(dateOfBirth);
motherField.setText(mother);
fatherField.setText(father);
brothersField1.setText(brother1);
brothersField2.setText(brother2);
brothersField3.setText(brother3);
brothersField4.setText(brother4);
brothersField5.setText(brother5);
sisterField1.setText(sister1);
sisterField2.setText(sister2);
sisterField3.setText(sister3);
sisterField4.setText(sister4);
sisterField5.setText(sister5);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
And this is when I try to get the same results of System.out.println as before:
private void brotherViewButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Memory mem = new Memory();
String sql = "select * from userInfo where id=?";
pst=conn.prepareStatement(sql);
String IDNO = mem.brother1ID;
System.out.println(IDNO);
pst.setString(1, IDNO);
rs=pst.executeQuery();
if(rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String placeOfResidence = rs.getString("placeOfResidence");
String employmentStatus = rs.getString("employmentStatus");
String currentEmployer = rs.getString("currentEmployer");
String taxStatus = rs.getString("taxStatus");
String dateOfBirth = rs.getString("dateOfBirth");
String mother = rs.getString("mother");
String father = rs.getString("father");
String brother1 = rs.getString("brother1");
String brother2 = rs.getString("brother2");
String brother3 = rs.getString("brother3");
String brother4 = rs.getString("brother4");
String brother5 = rs.getString("brother5");
String sister1 = rs.getString("sister1");
String sister2 = rs.getString("sister2");
String sister3 = rs.getString("sister3");
String sister4 = rs.getString("sister4");
String sister5 = rs.getString("sister5");
System.out.println(firstName + " " + lastName);
firstNameField.setText(firstName);
lastNameField.setText(lastName);
placeOfResidenceField.setText(placeOfResidence);
employmentStatusField.setText(employmentStatus);
currentEmployerField.setText(currentEmployer);
taxStatusField.setText(taxStatus);
dateOfBirthField.setText(dateOfBirth);
motherField.setText(mother);
fatherField.setText(father);
brothersField1.setText(brother1);
brothersField2.setText(brother2);
brothersField3.setText(brother3);
brothersField4.setText(brother4);
brothersField5.setText(brother5);
sisterField1.setText(sister1);
sisterField2.setText(sister2);
sisterField3.setText(sister3);
sisterField4.setText(sister4);
sisterField5.setText(sister5);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
The reason the value brother1ID in your Memory object is null is because you're using a new instance of that object.
I strongly recommend you read up on how object instances are scoped in Java, and what it means to create a new instance, versus using an existing one.
For example, when you do this:
Memory mem = new Memory();
mem.brother1ID = "1234";
mem = new Memory();
System.out.println(mem.brother1ID);
The value printed will be null. This is because you're using a new instance of that class. If you wanted to maintain the values throughout multiple method calls, your best bet might be to save the Memory object as an instance variable of whatever class contains the methods you've shown. i.e.:
private Memory memory = new Memory();
...
private void searchFieldKeyReleased(java.awt.event.KeyEvent evt) {
// Use 'this.memory'
this.memory.brother1ID = "1234";
//(or)
System.out.println(this.memory.brother1ID);
}
private void brotherViewButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Use 'this.memory'
}
Please look at here
try {
Memory mem = new Memory();
String sql = "select * from userInfo where id=?";
pst=conn.prepareStatement(sql);
String IDNO = mem.brother1ID;
System.out.println(IDNO);
You are creating the object of Memory and not setting any value.
then you are trying to print the brotherId which will be null, all String variables will be initialised to null, that is why you are getting 'null'. what you can do is put the printing statement out of the try catch block at he bottom , if there are any records in your database, it will print out the last records brotherId.

How do I fix a java.lang.NumberFormatException: for String " " in my servlet?

I keep running into the same error after trying to parse a String parameter I pulled from a corresponding jsp and make them into an integer and a float. In my web application I have java classes where the values I'm trying to parse are an integer and a float, but I can't seem to find a way to parse them and have my servlet work the way I'd like it to. Here's the code I used in my servlet:
//get Parameter from newStudentPage.jsp
String id = request.getParameter("stuId");
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String street = request.getParameter("street");
String city = request.getParameter("city");
String state = request.getParameter("state");
String zip = request.getParameter("zip");
String email = request.getParameter("email");
String gpa = request.getParameter("gpa");
int Zip = Integer.valueOf(zip);
float GPA = Float.parseFloat(gpa);
//Use RequestDispatcher to forward to jsp's
RequestDispatcher rd = request.getRequestDispatcher("newStudentLoginPage.jsp");
RequestDispatcher rd2 = request.getRequestDispatcher("newStudentSectionAddDrop.jsp");
//Create Student object and fill with paramater data
Student s2 = new Student();
s2.setstuId(id);
s2.setfName(fName);
s2.setlName(lName);
s2.setstreet(street);
s2.setcity(city);
s2.setstate(state);
s2.setzip(Zip);
s2.setemail(email);
s2.setgpa(GPA);
//Put Student object into Session
HttpSession ses2 = request.getSession();
ses2.setAttribute("s2", s2);
if(id.equals("")||fName.equals("")||lName.equals("")||street.equals("")||city.equals("")||state.equals("")||zip.equals("")||email.equals("")||gpa.equals("")){
rd.forward(request, response);
}else{
rd2.forward(request, response);
}
Can anyone please offer my some insight to what I'm doing wrong?
One or all of these lines can cause the exception:
int Zip = Integer.valueOf(zip);
float GPA = Float.parseFloat(gpa);
You need to check if String zip or gpa can always be converted into a number. What if the user enters nothing, i.e "", " "or a non-number like seven777 ? Those conditions will cause a NumberFormatException.
You should catch the exception and do something, i.e. provide a default value, ask the user to enter a valid value, etc...
Float floatGpa = null;
try {
floatGpa = Float.parseFloat(gpa);
} catch (NumberFormatException e) {
//do something
}

How do I calculate total hours in a GUI-based program?

I am creating a simple GUI-based time card. So I already have the implementation (given by a friend) but it was just made in a non-GUI program.
System.out.print("Enter time-in: ");
String strTimein = input.next();
String timeInArr[] = strTimein.split(":");
double dblTimeInHr = Double.parseDouble(timeInArr[0]);
double dblTimeInMin = Double.parseDouble(timeInArr[1]);
double dblTotalTimeIn = dblTimeInHr + (dblTimeInMin/60);
System.out.print("Enter time-out: ");
String strtimeout = input.next();
String timeOutArr[] = strtimeout.split(":");
double dblTimeOutHr = Double.parseDouble(timeOutArr[0]);
double dblTimeOutMin = Double.parseDouble(timeOutArr[1]);
double dblTotalTimeOut = dblTimeOutHr + (dblTimeOutMin/60);
totalHrs = totalHrs + (dblTotalTimeOut - dblTotalTimeIn);
It works actually. But I couldn't get it to work when I apply it now on my GUI-based program. So I have two JTextField, that is where the user will input the time-in and time-out. And another JTextField, total1, that is setEditable(false) where it will display the total hours.
total1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String timeIn = tIn1.getText();
String timeInArr[] = strtimein.split(":");
double dblTimeInHr = Double.parseDouble(timeInArr[0]);
double dblTimeInMin = Double.parseDouble(timeInArr[1]);
double dblTotalTimeIn = dblTimeInHr + (dblTimeInMin/60);
String timeOut = tOut1.getText();
String timeOutArr[] = strtimeout.split(":");
double dblTimeOutHr = Double.parseDouble(timeOutArr[0]);
double dblTimeOutMin = Double.parseDouble(timeOutArr[1]);
double dblTotalTimeOut = dblTimeOutHr + (dblTimeOutMin/60);
totalHours = totalHours + (dblTotalTimeOut - dblTotalTimeIn);
tal1.setText(totalHours);
}
});
The error I'm getting is "cannot find symbol" which points to:
String timeInArr[] = strTimein.split(":");
and
String timeOutArr[] = strTimeOut.split(":");
I know there's something wrong with my code, but I couldn't figure it out. Please help.
strtimein is not declared anywhere, you probably meant to use timeIn.
You have not declared those two strings in your code..
create these two strTimeOut and strTimeIn
Seems you actually wanted to use timeIn and timeOut
Well....
String timeIn = tIn1.getText();
String timeInArr[] = strtimein.split(":");
I guess you want to split the content of the textfield tIn1, so you should not use strtimein but timeIn. strtimein is not declared anywhere and that's what your error message says.
String timeInArr[] = timeIn.split(":");
The same goes for timeOut / strTimeOut below

Categories

Resources