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

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

Related

Java cast a string as a double [duplicate]

This question already has answers here:
Convert String to double in Java
(14 answers)
Closed 1 year ago.
Im creating a basic GUI that takes the amount entered by a user and subtracts it with a pre existing amount. However it will not let me to run the one below as I get an error of String cannot be converted to double. Using the parseInt method won't work here as im using the getText Method.
String message = txtaMessage.getText();
String transaction1 = txtfAmountTransfer.getText();
String reciever = txtfTransferTo.getText();
lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
lblOutputTransferMsg.setText("With a Message: "+ message);
double balance = 5123.84;
String newBalance = balance - transaction1;//this will not work but the concept I need
lblSavingsBalance.setText(newBalance);
It won't work because here transcation1 is a string and whereas balance is double. In java, we don't have a method to subtract string from double. So, First, you need to convert transaction1 into double. I suggest you to
Double newBalance = balance - Double.parseDouble(transcation1);
then lblSavingsBalance.setText(newBalance.toString()); to convert newBalance double value to string
Hope it works fine...
If getText returns String below code will work.
String message = txtaMessage.getText();
String transaction1 = txtfAmountTransfer.getText();
String reciever = txtfTransferTo.getText();
lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
lblOutputTransferMsg.setText("With a Message: "+ message);
double balance = 5123.84;
balance = balance - Double.parseDouble(transaction1);//this will not work but the concept I need
lblSavingsBalance.setText(String.valueOf(balance));
If you are using android,
(Assuming txtaMessage, transaction1, reciever are either TextView objects or EditText objects)
txtaMessage.getText(); //This won't return a String. This will return a CharSequence.
You have to convert it to string. So the correct method is,
String message = txtaMessage.getText().toString();
Do this for all EditTexts and TextViews.
Then transaction1 shoud be converted as Double
Double.parseDouble(transaction1);
After that you can substract transtraction1 from balance and assign it to the original balance.
balance = balance - Double.parseDouble(transaction1)
The full version of android code is below.
String message = txtaMessage.getText().toString();
String transaction1 = txtfAmountTransfer.getText().toString();
String reciever = txtfTransferTo.getText().toString();
lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
lblOutputTransferMsg.setText("With a Message: "+ message);
double balance = 5123.84;
balance = (balance - Double.parseDouble(transaction1));//this will not work but the concept I need
lblSavingsBalance.setText(String.valueOf(balance));
If the transaction1 value is not a number, An Exception will occur. So wrapping it with try/ catch is a good idea.
try {
balance = (balance - Double.parseDouble(transaction1));//this will not work but the concept I need
lblSavingsBalance.setText(String.valueOf(balance));
} catch (NumberFormatException e) {
//Send error message like showing a toast
e.printStackTrace();
}

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

How to debug a JOption error message in 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.

Getting a part of a string in java

so, right now I have this String:
String csfo = "([csfo_num = 333015303][ csfo_minimum = 4044504600][ csfo_offering = 48526][csfo_add_ind A])";
I want to be able to get just this part of the the string but I'm at a loss as to how to do this.
Needed Output:
String[] requiredOutput;
requiredOutput[1] = 48526; // csfo_offering
requiredOutput[2] = csfo_add_ind A;
or
requiredOutput[2] = A; // csfo_add_ind
EDIT:
I have used some of your suggestions and am trying out subString but it seems like its a temp fix because if the length of the original string changes then it will throw a wrench in my calls. I will try regex next because it seems to go by pattern matching and I might be able to figure something out with that. Thanks everyone for all your help.
Suggestions are still appreciated!
Are the numbers always the same length? If so, use String.subString. If not use String.indexOf("csfo_add") to find the locations of the "csfo_add" parts and then find the relative locations of the required information.
Hi there you can also use split if you always have the same pattern for your string.
for example
String csfo = "([csfo_num = 333015303][ csfo_minimum = 4044504600][ csfo_offering = 48526][csfo_add_ind A])";
System.out.println(csfo.split("csfo_add_ind ")[1].split("\\]\\)")[0]);
Would get the requiredOutput[2] = A; // csfo_add_ind
and this would get the first one
String[] requiredOutput = new String[2];
String csfo = "([csfo_num = 333015303][ csfo_minimum = 4044504600][ csfo_offering = 48526][csfo_add_ind A])";
requiredOutput[0] = "csfo_add_ind " + csfo.split("csfo_add_ind ")[1].split("\\]\\)")[0];
requiredOutput[1] = csfo.split("\\]\\[csfo_add_ind ")[0].split("csfo_offering = ")[1];
//System.out.println(requiredOutput[0] + " et " + requiredOutput[1] );

difference between two times in java

I have searched and found a lot of different things but none that actually help to get what I am looking for. I have two JComboBoxes in which the user can select different times. For example lets say 8:00, and 17:30. Now I want to be able to display the difference between those times, so in this case it would be 9.5. I want it to be in the 9.5, and not 9:30. But my code is doing 9.3, because it is just converting my string to a double.
Any help would be great
public void displaytotal() {
Object sunBobj, sunEobj, mon, tues, wed, thur, fri, sat;
double totalD;
sunBobj = jComboBox1.getSelectedItem();
sunEobj = jComboBox2.getSelectedItem();
String sunB = sunBobj.toString();
String sunE = sunEobj.toString();
try {
double sundB = Double.parseDouble(sunB.replace(":", "."));
double sundE = Double.parseDouble(sunE.replace(":", "."));
totalD = ((sundE - sundB)) * 24;
String totalS = "" + totalD;
jLabel17.setText(totalS);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
You could split the hh:mm string in hours / minutes:
String[] time = sunB.split(":");
int hours = Integer.parseInt(time[0]);
int minutes = Integer.parseInt(time[1]);
double decimalTime = hours + minutes / 60.0;

Categories

Resources