Condition Error - java

i am trying to have a check on that if value is null then don't show the message and recall the constructor, i did the following way but its not working.
if (title == null) {
JOptionPane.showMessageDialog(null, "Please Enter All Values");
new InfoFrame();
}
else {
try {
System.out.println(title+""+date);
System.out.println(title+""+date);
s.execute("INSERT INTO task ([title],[deadline],[priority],[time]) VALUES ('"+ title+ "','"+ date+ "','"+ priority + "','"+ time + "')");
JOptionPane.showMessageDialog(null,"Your Task has been added to the Database:");
} catch (Exception e) {
System.out.println(e.getMessage());
}
*Edited the var Title like stupid naming conventions

if (Title.isEmpty()) {
Will do the trick.
If you want to check both null or empty
if (Title == null || Title.isEmpty()) {
Also its better to start your variable in simple letters.

Related

Java ternary operator badly evaluating null

I had a weird situation today while I was writing tests. Basically, I had a class with data. Let's say Toy for example, from which we can retrieve a name:
public class Toy {
private String name;
public Toy(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And I had an exception, which was working in a way similar to this (e.g. just displaying data about all the objects on which we were working before it went bad); I also included a main for test purpose:
public class ToyFactoryException extends Exception {
public ToyFactoryException(Toy firstToy, Toy secondToy) {
super("An error occurred when manufacturing: " +
"\nfirstToy: " + firstToy != null ? firstToy.getName() : null +
"\nsecondToy: " + secondToy != null ? secondToy.getName() : null);
}
public static void main(String[] args) {
try {
throw new ToyFactoryException(null, new Toy("hi"));
} catch (ToyFactoryException myException) {
System.out.println("It should be there.");
} catch (Exception exception) {
System.out.println("But it's there instead.");
}
}
}
As I wrote in the first catch block, the exception should be caught in the ToyFactoryException.
However, in the exception, it's trying to read firstToy.getName() right here: firstToy != null ? firstToy.getName() : null
firstToy != null should evaluate to false, which means it shouldn't be trying to call firstToy.getName() in the first place. When you write it in the reverse order:
public ToyFactoryException(Toy firstToy, Toy secondToy) {
super("An error occurred when manufacturing: " +
"\nfirstToy: " + firstToy != null ? null : firstToy.getName() +
"\nsecondToy: " + secondToy != null ? secondToy.getName() : null);
}
You realise it reads null instead now, which means it's truly reading firstToy != null as true.
If you write the main this way instead (the null is the second parameter of the constructor):
public static void main(String[] args) {
try {
throw new ToyFactoryException(new Toy("hi"), null);
} catch (ToyFactoryException myException) {
System.out.println("It should be there.");
} catch (Exception exception) {
System.out.println("But it's there instead.");
}
}
It works properly, despite the secondToy ternary condition being written the same way as the firstToy ternary.
Why is the ternary condition on firstToy not evaluating null properly?
You should put parentheses around your conditional expression.
This:
"string " + firstToy != null ? firstToy.getName() : null
means this:
("string " + firstToy) != null ? firstToy.getName() : null
You need this:
"string " + (firstToy != null ? firstToy.getName() : null)

My JSP if-else statement is not working properly

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 !!

Validation when Creating an Account JAVA

So there is this certain part of my program where I can create an account and the created account will be inserted into my database. And I'm trying to code something where *refer to the code:
public void actionPerformed(ActionEvent e) {
String user = userField.getText().trim();
String pass = passField.getText().trim();
String conPass = confirmPass.getText().trim();
try{
// TODO Auto-generated method stub
if(e.getSource()==submit){
if (user.equals(user)&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if the pass field is blank
else if(user.length()<5){
JOptionPane.showMessageDialog(null,"Username must be at least 5 characters!");
}
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
GUI gui = new GUI();
}//if(pass.equals(conPass))
else if(user.length()==0&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if both fields are blank
else if (user.length()==0 &&pass.equals(pass)){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if user field is blank
else if(user.equals(user)&&pass!=conPass){
JOptionPane.showMessageDialog(null, "Password do not match!");
}//check if password and confirm pass matches
}
I dont really know how to say the problem but look in the if and else if statements, if the user meet one the those conditions, the program should print the JOptionPane thing. Except for the second else if.
You might be wondering why I put these codes at my else if
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
The reason for this is that, my program is having some logic error when I try to put it in if statement. Please help me with my code thanks :) Feel free to write a new code for me :DD
i might try something like this:
public static boolean isSet(String s){
if(s==null || "".equals(s)) return false;
return true;
}
//.... your validation here
if(isSet(user) && isSet(pass) && isSet(conPass) && pass.equals(conPass)){
//create account
}else{
//smth wrong eg. if(!pass.equals(conPass) { //wrongpass }
}

how to call recursively a method in a try-catch block

hi i have this problem i got a method that let a user insert a value representing the "quantity" of a product, now if the quantity wanted by the user is higher then the stock quanity it has to throw an exception and let the user input again the number i tryed it inserting a recursive call of the same method but even if it success it goes in an infinite loop like the exception is still "alive"
...
try {
if (!lol2)
throw new NegativeNumberException();
} catch (NegativeNumberException pto) {
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
this.addToCart(cart,quant);
}
EDIT i am including now all the code but it's a bit hard so sry for the "complexity" of the code
FULL CODE
public void addToCart(ArrayList<Utilizzabile> cart,ArrayList<Integer> quant) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
boolean lol=false;
Utilizzabile us=null;
String id = JOptionPane.showInputDialog(frame, "Inserisci un ID prodotto:");
if (id ==null) { return;}
while (!id.matches("[0-9]+")) { //user inserts a value and the while checks for an int value inserted
JOptionPane.showMessageDialog(frame, "Valore inserito errato");
id = JOptionPane.showInputDialog(frame, "Inserisci un ID prodotto:");
if (id == null) { return;} }
int iden = Integer.parseInt(id);
for (Utilizzabile u: arr) { // this for loop checks if the ID inserted represents a product in the catalog
if ((u.getId() == iden) && (u.eAcquistabile())) {
lol =true;
us = u; } }
if (lol == true) { //now if the ID corresponds to an existent product it ask the user to input the quantity requested
boolean lol2=false;
String qua = JOptionPane.showInputDialog(frame, "Inserisci un quantità da aggiungere al carrello:");
if (qua ==null) { return;}
while (lol2==false) {
while (!qua.matches("[0-9]+")) {
JOptionPane.showMessageDialog(frame, "Valore inserito errato");
qua = JOptionPane.showInputDialog(frame, "Inserisci un quantità da aggiungere al carrello:");
if (qua == null) { return;} }
if (qua.length()>0 && qua.length()<=8) {
int quantit = Integer.parseInt(qua);
for (int l=0;l<cart.size();l++) { //this for checks if in the cart were already that product and then changes the quantities only
if ((cart.get(l).getId() == us.getId()) && (us.getRem()-quantit >0) ) {
int num = quant.get(l)+quantit;
quant.set(l,num);
JOptionPane.showMessageDialog(frame, "Quantità del prodotto richiesto aggiornata");
return;}
}
if ( (us.getRem()-quantit) >0) { //checks if all went good and the quantity is avaiable
JOptionPane.showMessageDialog(frame, "Prodotto della quantità richiesta aggiunto al carrello");
lol2=true;
cart.add(us);
quant.add(quantit);} }
try {
if (lol2==false)
throw new NegativeNumberException(); }
catch (NegativeNumberException pto){
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
this.addToCart(cart,quant); }
} }
else {
JOptionPane.showMessageDialog(frame, "Prodotto non trovato");
this.addToCart(cart,quant); }
}
this code essentially is a graphical section for let the user add a product to the cart and check is everything is good but i need to place an exception to check if the quantity in stock is less then the quantity wanted by the user (i ve done it without exception with no problems but this is for an exam and i just noticed that the professor wants that i have to solve this problem by using an exception
It's not good to use recursion for that, because after "n" invocations you can receive StackOverFlowError. And I agree with #laune.
Thus I recommend to use loop. For example:
while (true){
// lol2 here is TRUE if was entered correct value and false if not.
if (lol2)
break;
else {
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
this.addToCart(cart,quant);
}
}
insert try catch into do while loop.
when user insert correct value stop loop
E.g
int a=10;
do{
try{
if(a<20)
throw new NegativeNumberException();
else
break;
}catch (NegativeNumberException pto){
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
//enter quantity again
// a=20;
}
}while(true);
Never use exceptions to control the regular or almost regular flow of control. It's bad programming style.
Use some do statement to repeat the dialog until a satisfactory input is achieved.
Due to lack of context, no code is provided. (Where is that recursive call??)
Later
There is room for exception handling, though. You could throw away pattern matching and length check and catch NumberFormatException.
Integer quantity = null;
do {
String id ... dialogue
try {
quantity = Integer.parseInt( id );
if( quantity <= 0 ) throw new NumberFormatException( "only positive integers" );
} catch( NumberFormatException nfe ){
... error dialogue;
quantity = null;
}
} until( quantity != null );

How to find the number of vote up or vote down for a youtube comment through API

I am fetching the comments for a video using Youtube's Java API. I want to know can I find the number of up votes or down votes for all the comment. If yes then how. Currently I am using the code given below. I am getting totalRating for each comment to find upvotes but every-time it outputs 0. I know this is wrong but how do I get the vote up and down for comments.Any pointers in the right direction will be appreciated. Thanks.
private void AddComments(YouTubeVideo ytv,VideoEntry videoEntry,YouTubeService service)
{
try
{
//Get Comments
String commentUrl = videoEntry.getComments().getFeedLink().getHref();
LinkedList<YouTubeComment> commentsLinkedList = new LinkedList<YouTubeComment>();
if(commentUrl!= null && commentUrl.length() > 0)
{
CommentFeed commentFeed = service.getFeed(new URL(commentUrl), CommentFeed.class);
if(commentFeed != null)
{
for(CommentEntry comment : commentFeed.getEntries())
{
YouTubeComment youtubeComment = new YouTubeComment();
if(comment.getTotalRating()!=null)
**//comment.getTotalRating() is always equal to 0.**
youtubeComment.setLike(comment.getTotalRating());
else
youtubeComment.setLike(0);
youtubeComment.setSpamStatus(comment.hasSpamHint());
String commentinVideo = comment.getPlainTextContent();
if(commentinVideo != null)
youtubeComment.setComment(comment.getPlainTextContent());
else
youtubeComment.setComment(" ");
commentsLinkedList.add(youtubeComment);
}
ytv.setComments(commentsLinkedList);
}
else
ytv.setComments(commentsLinkedList);
}
else
{
ytv.setComments(commentsLinkedList);
}
}
catch(Exception ex)
{ // This means that "Comments are disabled for this video."
LinkedList<YouTubeComment> comments = new LinkedList<YouTubeComment>();
ytv.setComments(comments);
System.out.println("Could not add comments for video := " + videoUrl);
System.out.println("This happens when comments are disabled for the video");
System.out.println("Exception in function AddComments : " + ex.toString());
}
}
Unfortunately, those values are not exposed via the API, and there are no plans to add them.

Categories

Resources