I'm attempting to add an ArrayList to an object with a do...while loop. Unfortunately I continue to get a validation error each time I run the program.
Here is the function that I am using to add an ArrayList to the object DVD:
public DVD getNewDVDInfo() {
String title = io.readString("Please enter DVD title");
String releaseDate = io.readString("Please enter Release Date (mm-DD-yyyy)");
LocalDate ld = LocalDate.parse(releaseDate, DateTimeFormatter.ofPattern("mm-DD-yyyy"));
String mpaaRating = io.readString("Please enter MPAA Rating");
String directorName = io.readString("Please enter Director's Name");
String studio = io.readString("Please enter Studio");
boolean hasNext = true;
ArrayList<String> userRating = new ArrayList<>();
String userRatingString = io.readString("Please enter User Rating");
userRating.add(userRatingString);
DVD currentDVD = new DVD(title);
currentDVD.setReleaseDate(ld);
currentDVD.setMpaaRating(mpaaRating);
currentDVD.setDirectorName(directorName);
currentDVD.setStudio(studio);
currentDVD.setUserRating(userRating);
return currentDVD;
}
The validation method:
private void validateDVDData(DVD dvd) throws DVDLibraryDataValidationException {
if (dvd.getTitle() == null || dvd.getTitle().trim().length() == 0
|| dvd.getReleaseDate() == null
|| dvd.getMpaaRating() == null || dvd.getMpaaRating().trim().length() == 0
|| dvd.getDirectorName() == null || dvd.getDirectorName().trim().length() == 0
|| dvd.getStudio() == null || dvd.getStudio().trim().length() == 0
|| dvd.getUserRating()== null || dvd.getUserRating().isEmpty()); {
throw new DVDLibraryDataValidationException("ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name, Studio, User Rating] are required");
}
}
Every time I run the app, the error message is thrown.
Any help would be much appreciated.
To identify your problem you could use a debugger but you could also improve the way of doing the check.
Instead of doing a global error :
ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name,
Studio, User Rating] are required");
it would be more helpful to the user (and also to you for tracing the information) to know where is exactly the problem in the provided values.
In your DVDLibraryDataValidationException class, you could add a List of String field where you add the error field names.
And you could override getMessage() of this class to provide a helpful message indicating the fields with validation error.
Just to give an idea on the way to start :
List<String> errorFields = new ArrayList<>();
if (dvd.getTitle() == null || dvd.getTitle().trim().length() == 0){
errorFields.add("title");
}
if (dvd.getReleaseDate() == null ){
errorFields.add("release date");
}
...
if (!errorFields.isEmpty()){
throw new DVDLibraryDataValidationException("ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name, Studio, User Rating] are required",
errorFields);
}
Related
My application cannot find the roommate I added to the room, see sequence:
Please select one of the following options:
Add a room in the apartment[1]
Search for a room in the apartment[2]
Add a roommate to an existing room[3]
Check if a room has a roommate[4]
Count the number of existing rooms that have roommates living in them[5]
3
What is the name of this roommate?
kack
What is the surname of thid roommata?
han
What is the age of this roommate?
20
Which room you want to add this roommate in?[A]/[B]/[C]
b
The roommate was added to the room!
Do you want to continue using the App? (Y/N)
y
Please select one of the following options:
Add a room in the apartment[1]
Search for a room in the apartment[2]
Add a roommate to an existing room[3]
Check if a room has a roommate[4]
Count the number of existing rooms that have roommates living in them[5]
4
What is the ID of the room?[A]/[B]/[C]
b
Sorry! There is no roommate in this room.
I am not sure where I have to rewrite. I want to know which part is wrong and how I should rewrite my code. The code is following, and the first part is to add roommate and the second part is to check if there is a roommate in the room:
public boolean addRoommate(String pName, String pSurname, int pAge, char pID) {
boolean response = false;
if (roomA != null && roomA.getID() == (pID)) {
Roommate newRoommate = new Roommate(pName, pSurname, pAge);
response = true;
} else if (roomB != null && roomB.getID() == (pID)) {
Roommate newRoommate = new Roommate(pName, pSurname, pAge);
response = true;
} else if (roomC != null && roomC.getID() == (pID)) {
Roommate newRoommate = new Roommate(pName, pSurname, pAge);
response = true;
}
return response;
}
Here is the second part of the code, which is where I check for roommate:
public Roommate checkRoommate(char pID) {
Roommate response = null;
if (roomA != null && roomA.getID() == (pID) && roomA.getRoommate() != null) {
response = roomA.getRoommate();
} else if (roomB != null && roomB.getID() == (pID) && roomB.getRoommate() != null) {
response = roomB.getRoommate();
} else if (roomC != null && roomC.getID() == (pID) && roomC.getRoommate() != null) {
response = roomC.getRoommate();
}
return response;
}
You need to put the rommate into a rool, for example this way:
roomA.setRoomMate(newRoommate)
I am new to JSP and I want to validate an HTML form using JSP, I am using an if-else statement in my code. But it's not working properly.
<%
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
String uname = request.getParameter("username");
String pw = request.getParameter("password");
String pw1 = request.getParameter("confirm");
String phone = request.getParameter("phone");
String idno = request.getParameter("idno");
String gender = request.getParameter("gender");
String dob = request.getParameter("dob");
String bgroup = request.getParameter("bloodgroup");
String bweight = request.getParameter("weight");
String lastdonate = request.getParameter("lddate");
if (request.getParameter(fname) == null
|| request.getParameter(lname) == null
|| request.getParameter(email) == null
|| request.getParameter(uname) == null
|| request.getParameter(pw) == null
|| request.getParameter(pw1) == null
|| request.getParameter(phone) == null
|| request.getParameter(idno) == null
|| request.getParameter(dob) == null
|| request.getParameter(bweight) == null
|| request.getParameter(lastdonate) == null) {
out.println("<div class='alert-message alert-message-warning' align='center'>"+
"<h4>Alert Message Warning</h4>"+
"<p>Some Fields Are Empty <br>" +
"<strong>Please Fill All The Fields</strong>."+
"</p></div>");
}
else if (request.getParameter(pw) != request.getParameter(pw1) ) {
out.println("<div class='alert-message alert-message-warning' align='center'>"+
"<h4>Alert Message Warning</h4>"+
"<p>Confirmed Password Doesn't Match With the Password <br>" +
"<strong>Please Re-Type Your Password</strong>."+
"</p></div>");
}
else {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
System.out.println(ex);
}
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/minutehelp","root","");
Statement stm = con.createStatement();
stm.executeUpdate("INSERT INTO donors VALUES(NULL, '"+fname+"', '"+lname+"', '"+email+"', '"+uname+"', '"+pw1+"', '"+phone+"', '"+idno+"', '"+gender+"', '"+dob+"', '"+bgroup+"', '"+bweight+"', '"+lastdonate+"')");
stm.close();
} catch (Exception ex) {
out.println(ex);
}
}
%>
First I want to check whether all the fields are empty or filled, then I want to check whether the password and confirmed passwords are same and if there are no errors with these I want to send these data to my database table 'donors'. But it's not working properly and it always displays the warning message inside the if statement and data is not being inserted. But if I use only if statements instead of if-else, it always displays the first warning message and inserts data each time even if conditions were false.
I am very new to JSP, please someone help me here.
Thank you.
Problem in your if statement is that you are trying to compare i.e request.getParameter(fname) and so on . but that doesn't exist. if you want to compare put " " this in your request.getParameter("something")
Also if you want to compare using variable in your case fname,pw,pw1 etc. try doing something like this
if(fname==null || uname==null ... ){
//do something
}
Now to see if value of password are equal try doing this in your else-if
else if (pw.equals(pw1) ) {
//do something
}
Also,you can modify your code like this to achieve what you want
if(fname!=null || uname!=null ...){
if (pw.equals(pw1) ) {
//your insert code put here
}else{
out.println("<div class='alert-message alert-message-warning' align='center'>"+
"<h4>Alert Message Warning</h4>"+
"<p>Confirmed Password Doesn't Match With the Password <br>" +
"<strong>Please Re-Type Your Password</strong>."+
"</p></div>");
}
}else{
out.println("<div class='alert-message alert-message-warning' align='center'>"+
"<h4>Alert Message Warning</h4>"+
"<p>Some Fields Are Empty <br>" +
"<strong>Please Fill All The Fields</strong>."+
"</p></div>");
}
Hope this helps !!
name = full_name_input.getText();
Fname = father_name_input.getText();
cnic = father_cnic_input.getText();
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
prsnt_add = present_add_input.getText();
city = city_input.getText();
province = radio_text;
if(name.equals("") || Fname.equals("") || cnic.equals("") || DOB==0 || Class_V==0 || prsnt_add.equals("") || city.equals("") || province.equals(""))
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Please fill all fields ! \n");
}
radio_text here is actually input from radio button and it is giving an error
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
actually i want to ensure that none of the jfields remain empty by the user
and if any field remains undefined it shows a popup please fill all fields
but when date of birth or class field or both remain unfiilled by the user it gives an error mentioned in the preeceding paragraph
What's happening is you're checking your fields after you try to set them, but the error occurs before that. For example, if DOB_input's text is "", DOB will throw an error trying to parse that (Integer.parseInt() can't deal with strings like that) before you see that it's empty. If you want to keep your if-statement, you'll have to move it above the lines where you set your values. However, to do that you'd need to tweak it a bit so you check the jfields' values. Like:
if(full_name_input.getText().equals("") || father_name_input.getText().equals("") ..... )
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Please fill all fields ! \n");
}
I bet you have a problem here:
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
Either DOB_input or class_input (or even both of them) getText() returns empty string. You should catch that exception and properly handle it like this:
try {
value = Integer.parseInt(input.getText());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Illegal nuber format for field <field>");
return;
}
There is a problem with parsing number from String.
Did you check on which line this happened?
I suppose that here:
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
I have the following method
public Message JavaMethod(String id1, String id2)
In which I need to call a Dao class's method to verify that an user with the provided Id exist, and if it does not, create a message detailing the Id that couldn't be found on the database with the following method:
createMessage("Message string",Enum.TYPE,IdofMissingUser);
At first I thought of doing it like this:
public Message JavaMethod(String id1, String id2) {
if(Dao.findUser(id1) == null || Dao.findUser(id2) == null){
return createMessage("Error",Enum.Error,id1);
}else{
//do some other stuff
}
}
But obviously this way I won't know which of the ids has not been found.
So I went ahead and created an ugly if else cycle:
public Message JavaMethod(String id1, String id2) {
if (Dao.findUser(id1) == null) {
return createMessage("Error", Enum.Error, id1);
} else if (Dao.findUser(id2) == null) {
return createMessage("Error", Enum.Error, id2);
} else {
// Do stuff after veryfing users exists
return createMessage("All OK", Enum.OK, messageData);
}
}
But I'm not feeling really confident that this is the best solution for this basic issue.
What would you guys recommend in this case?
You could wrap the ids in a list and use a for loop:
public Message someMethod(String id1, String id2) {
for (String id: Arrays.asList(id1, id2)) {
if (Dao.findUser(id) == null) {
return createMessage("Error", Enum.Error, id);
}
}
// Do stuff after verifying users exists
return createMessage("All OK", Enum.OK, messageData);
}
If you're only ever going to have two IDs, you could deal with a shorthand boolean. Question is whether that makes it less readable though. E.g.
public Message JavaMethod(String id1, String id2) {
User user1 = Dao.findUser(id1);
User user2 = Dao.findUser(id2);
if(user1 == null || user2 == null){
return createMessage("Error",Enum.Error,user1 == null ? id1 : id2);
}else{
//do some other stuff
}
}
This also doesn't deal with if both of the IDs were null, for that you could extend it:
public Message JavaMethod(String id1, String id2) {
User user1 = Dao.findUser(id1);
User user2 = Dao.findUser(id2);
if(user1 == null || user2 == null){
return createMessage("Error",Enum.Error,user1 == null && user2 == null? both : user1 == null ? id1 : id2);
}else{
//do some other stuff
}
}
You'd need to define what you would return for the both variable
More details on the shorthand boolean annotation can be found here
I have a form and I put the forms data in an intent and then start a new activity and send the data with the intent, but I wanna do a check if the strings are empty I should display and error message. If the strings are not empty the activity can be started.
I've tried the following code but it doesn't seem to be working. If the field is empty it just starts the other activity
(I've tried with only 1 field for now, because I don't know how to to it for multiple fields)
//getting the field values
String firstname = editTextFirstname.getText().toString();
String lastname = editTextLastname.getText().toString();
String amount = editTextBedrag.getText().toString();
String timespan = spinnerPeriode.getSelectedItem().toString();
String iban = editTextIBAN.getText().toString();
if(firstname != null) {
//putting data in the intent
intent.putExtra(FIRSTNAME, firstname);
intent.putExtra(LASTNAME, lastname);
intent.putExtra(AMOUNT, amount);
intent.putExtra(TIMESPAN, timespan);
intent.putExtra(IBAN, iban);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
}
A cleaner way to do this is
public static boolean isAnyStringNullOrEmpty(String... strings) {
for (String s : strings)
if (s == null || s.isEmpty())
return true;
return false;
}
Then you can call it like this
if (isAnyStringNullOrEmpty(firstname, lastname, amount, timespan, iban)) {
Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
} else {
}
Using apache commons, we can do this as:
boolean valid = StringUtils.isNoneEmpty(firstname, lastname, amount, timespan, iban)
Change
if(firstname != null)
to
if(!TextUtils.isEmpty(firstname) && !TextUtils.isEmpty(lastname) &&
!TextUtils.isEmpty(amount) &&!TextUtils.isEmpty(timespan) &&
!TextUtils.isEmpty(iban))
Java 8 + Apache Commons Lang only:
String firstname = editTextFirstname.getText().toString();
String lastname = editTextLastname.getText().toString();
String amount = editTextBedrag.getText().toString();
String timespan = spinnerPeriode.getSelectedItem().toString();
String iban = editTextIBAN.getText().toString();
boolean valid = Stream.of(firstname, lastname, amount, timespan, iban)
.allMatch(StringUtils::isNotBlank);
if(firstname != null && lastname != null && amount != null && timespan != null
&& iban != null & firstname.trim().isEmpty() && !lastname.trim().isEmpty() &&
!amount .trim().isEmpty() && !timespan.trim().isEmpty() && !iban.trim().isEmpty())
Using Java Stream API:
private boolean anyBlank(String...strings) {
return Stream.of(strings).anyMatch(string -> isBlank(string));
}