if statement and user input advice - java

My user inputs work fine, my problem is I want an if statement that will say are both inputs equal?, but I get the attached error.
I need the code to be: if cork is entered in batman and robin?. This is what I tried:
System.out.println("From " + batman);
System.out.println("To " + Robin);
if(batman.equals("Cork") + Robin.equals("Cork") {
} else {
System.err.println("");
}

that here:
if(batman.equals("Cork") + Robin.equals("Cork") {
makes no sense because you are doing something like concatenating true with true or similar...
you have to do instead:
if(batman.equals("Cork") && Robin.equals("Cork") {

Your code should look like this :
System.out.println("From " + batman);
System.out.println("To " + Robin);
if(batman.equals("Cork") && Robin.equals("Cork")) {
// Statements
} else {
System.err.println("");
}

You should simply use && when requiring more then one test in an if statement.
+ doesn't work in such cases it simply concatenates values. Hope it helps :)

Related

Building Hibernate query depending of parameters that can be nulls

so i am working on a project right now
1st time using Hibernate
in this projet i am using Swing too
i have a form with multiple jTextFields
public List<Object[]> getoperations(String a,String c,String n,String e,String d) {
SessionDao s=new SessionDao();
session=s.getSession();
Query q;
q=session.createQuery("select idTiers,beneficiaire,emetteur,montant,numcompte,t_param_nature_operation.libelleNature,dateValidite,dateCreation where");
if (a != null && !a.isEmpty()) { q+= " and codeBanque='" + a + "'"; }
if (c != null && !c.isEmpty()) { q += " and numCompte='" + c + "'"; }
if (n != null && !n.isEmpty()) { q += " and t_param_nature_operation_.libelleNature='" + n + "'"; }
if (e != null && !e.isEmpty()) { q += " and decision='" + e + "'"; }
if (d != null && !d.isEmpty()) { q += " and dateCreation='" + d + "'"; }
q+= " order by idTiers" ;
return q.list();
}
As you see I am making a test on the values to add them in the query.
My question is there a way to add those values?
since query +="" isn't working.
Personally, I would add Guava utils to my project and use isNotBlank()
function. Anyway, you can write your own static function that would
return true if not null and not empty and false otherwise, and later
use it. It'll make your code much clearer.
The above was my comment and I decided to show you this little piece of code.
public static boolean isBlank(String s) {
if (s == null)
return true;
if (s.isEmpty())
return true;
return false;
}
Now you can simply write:
//static import your isBlank() method
//import static package.classInWhichIsBlankIsDeclared;
if (!isBlank(a) { q+= " and codeBanque='" + a + "'"; }
if (!isBlank(b) { q+= " and codeBanque='" + b + "'"; }
if (!isBlank(c) { q+= " and codeBanque='" + c + "'"; }
if (!isBlank(d) { q+= " and codeBanque='" + d + "'"; }
It's much more readable so it'll be much easier to debug in case of errors in the future.
Please, have a look at DRY principle and follow it. If your issue require checking same condition 4 or 5 times (2 times should be enough to use DRY) consider writing a function. call it the way that it'll be human-friendly instead of combination of different logical statements.
DRY. Don't Repeat Yourself.
"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system"
Wikipedia article about DRY
you should consider using Criteria. it's more clean when dealing with multiple where statements.
eg
Criteria cr = session.createCriteria(YourEntityClass.class);
cr.add(Restrictions.eq("property1", value1));
cr.add(Restrictions.eq("property2", value2));
List results = cr.list();
have a look at these examples here

How to disable pretty-printing in Groovy MarkupBuilder?

I have a string input in my Mule flow. It passes through my Groovy Script and outputs XML. I originaly had the script followed by an XSLT converter to remove empty nodes and set the indent to "no" in the output tag. But now I removed it as I cannot use it in conjunction with my script if I want to keep the special characters (see previous question here).
Instead I now check each value before printing the nodes. But the problem I have is my XML needs to be unindented in order to work with my InDesign project I adapt the XML for. I lost that ability when I removed the XSLT so I fixed one problem but created another.
I found the method getPrinter(), I used it with the setAutoIndent(false) but it didn't change anything to the output and created no errors. Not to sure where to use it.
Here's my script :
public Boolean isEmpty(value){
if(value.toString().trim() == "" || value.toString().trim() == '' || value == null)
return true;
}
root = new XmlSlurper(false,false).parseText(payload)
if(root.name() == 'GetActivitiesResponse')
startEach = root.children().children()
else
startEach = root.children()
def xml = new StringWriter().with { w -> new groovy.xml.MarkupBuilder(w).with {
mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
escapeAttributes = false
getPrinter().setAutoIndent(false);
"w_import_saisie_web"() {
startEach.each { p -> "w_evenement"() {
if(!isEmpty(p.PresentationDate))
"w_dates"{ mkp.yieldUnescaped (p.PresentationDate.toString() + "
") }
if(!isEmpty(p.SubTitle))
"w_contexte"{ mkp.yieldUnescaped (p.SubTitle.toString() + "
") }
//if(!isEmpty(p.SubTitle))
"w_nom_evenement"{ /*p.GEVT_Type*/ mkp.yieldUnescaped ("Nom evenement" + "
") }
if(!isEmpty(p.Name))
"w_titre"{ mkp.yieldUnescaped (p.Name.toString() + "
")}
if(!isEmpty(p.ShortDescription) || !isEmpty(p.Teaser))
"w_texte"{mkp.yieldUnescaped (p.ShortDescription.toString() + p.Teaser.toString() + "
")}
p.SubEvents.children().each { q -> "w_bloc_sous_evenement"() {
if(!isEmpty(q.PresentationDate) || !isEmpty(q.Name))
"w_sous_eve_titre"{ mkp.yieldUnescaped (q.PresentationDate.toString() + q.Name.toString() + "
")}
if(!isEmpty(q.ShortDescription) || !isEmpty(q.Teaser) || !isEmpty(q.WebDescription))
"w_sous_eve_desc"{mkp.yieldUnescaped (q.ShortDescription.toString() + q.Teaser.toString() + q.WebDescription.toString() + "
")}
}
}
if(!isEmpty(p.Site) || !isEmpty(p.PresentationHours))
"w_coordonnees"{ mkp.yieldUnescaped ("teeeessdfsdfsdfst" + p.Site.toString() + ' - ' + p.PresentationHours.toString() + "
")}
}
}
}
}
w.toString()
}
Add an IndentPrinter when you create the MarkupBuilder.
def xml = new MarkupBuilder(new IndentPrinter(new PrintWriter(writer), "", true))
See this question:
groovy.xml.MarkupBuilder disable PrettyPrint
I tried a bunch of different things to see if setAutoIndent was effective (setting it before passing the IndentPrinter to the MarkupBuilder for example) and it didn't seem to have any effect. So, like you, I'm wondering about its purpose.
Realised I was searching too hard... just added this simple line to the toString() at the end...
w.toString().replaceAll(">\\s+<", "><").trim();

Need to output prefix based on last letter of a noun

I am working on an assignment with an online Udacity course, where we have been asked to develop a method that recognizes the last letter of the noun and then based on the letter, out put a "La", "el", or "?" + the noun.
The complete instructions are You are to complete the method fixNoun in the SpanishWord class so that it returns the noun preceded by:
// "la " if the noun ends in "a",
// "el " if it ends in "o"
// "? " if it ends in some other letter.
I seem to keep getting all failures when compiling. Can someone please help me understand what I am doing wrong?
public String fixNoun(String noun) {
String determinenet= noun.substring(noun.length() - 1);
if(determinenet.equals("a")) {
System.out.println("la" + " "+noun );
}
else if ( determinenet.equals("o")) {
System.out.println( "el"+ " "+noun);
}
else {
System.out.println("?"+ " "+noun);
}
return noun;
}
you don't return the altered noun but the old one. In your code you have to change the
System.out.println("la" + " "+noun );
to
return("la " + noun);
and so on.
The fixed code looks like this:
public String fixNoun(String noun) {
String determinenet= noun.substring(noun.length() - 1);
if(determinenet.equals("a")) {
return("la" + " "+noun );
}
else if ( determinenet.equals("o")) {
return( "el"+ " "+noun);
}
else {
return("?"+ " "+noun);
}
}
}
P.S.: The String class has a method endsWith() that gives you the last character of the string.
So you also could write your code like this:
public String fixNoun(String noun) {
if(noun.endsWith("a")) {
return("la " + noun);
else if(noun.endsWith("o")) {
return("el " + noun);
else {
return("? " + noun);
}
}
Good luck with your assignment :)
I don't know maybe i'm wrong. how about this?
String de=noun.charAt(noun.length()-1)
if(de.equalsIgnoreCase("a"))
return "la" + " "+noun ;

Returning an Array results within a method

Problem solved.
I have two methods in my class.
private void retrieveDetails(){
List<String> details = File.getCredentials();
username = details.get(0);
pw = details.get(1);
}
private void checkCredentials() throws IOException {
retrieveDetails();
System.out.println("\nPlease enter USERNAME: ");
String usersName = scan.next();
System.out.println("\nPlease enter PASSWORD: ");
String usersPW = scan.next();
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw);
if (usersName.equals(username) && usersPW.equals(pw)) {
doWork();
} else {
System.out.println("Incorrect credentials");
}
}
I thought I came up with a solution by moving the following up to where my strings are initialized.
List<String> creds = File.getCredentials();
I created a System.out statement to check if the details coming from retrieveDetails() match those entered by the users. They do match - but when the system goes to the else clause instead of executing doWork();
If what is printed is the same then try trimming before comparing. E.g.:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
When i have similar problem i do this simple trick:
Print the size of the strings you are comparing because sometimes you have characters like \n or \r which are not visible when you print the string.
First of all, it seems like you have a typo in sysout statement below.
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw); //Should be username
Secondly, you might wanna trim the strings for better string comparison.
Sometimes strings read from file or console can contain unwanted and hard-to-catch empty strings like spaces and tabs. These can be removed by calling .trim() method on strings.
Thus, try using the following code instead:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
}
usersName.equals(username) && usersPW.equals(pw).
I have faced these problem also, These kind of equality always tricky, Try to trim the strings that you are going to compare, as well as if you can compare these strings based on their length.
if (usersName.trim().equalsIgnoreCase(username.trim()) && usersPW.trim().equalsIgnoreCase(pw.trim()))
or
if (usersName.trim().length()==username.trim().length && usersPW.trim().length()==pw.trim().length))

how to export a 2D table in java

hello i would like to ask you about the 2D tables in java!!my code is this an i would like to make a system out in order t see the registrations in mytable citylink can anyone help me?
int i=0;
while(i<=citylink.length) {
for(Xml polh_is:fetchsite.child("site").child("poleis").children("polh")) { //url
if((polh_is.string("name")=="")||(polh_is.content()==""))//attribute
error += "Error in polh: name is - " + polh_is.string("name") + " with url - " + polh_is.content() + " -.\n";
else
for(int j=0; j<citylink.length; j++) {
citylink[j][0]=HtmlMethods.removeBreaks(polh_is.string("name"));
citylink[j][1]=HtmlMethods.removeBreaks(polh_is.string("with url -"+polh_is.content() +"-.\n"));
i++;
}
}
}
citylink seems to be a single-dimensional array?
You can use another 2D array to store the values.
Something like this?:
StringBuilder citiesBuilder = new StringBuilder();
for (String[] city:citylink) {
citiesBuilder.append(String.format("%s (URL: %s)%n", city[0], city[1]));
}
System.out.println(citiesBuilder.toString());
EDIT
changed 'cities' to 'citylink' - my mistake. But trust me, it works ;) (Hope your Java is 1.5 at minimum)
ahh, and I assume, citylink is of type String[][]. Otherwise, please provide the declaration so I can adapt the code.
I don't understand the purpose of the second for loop: is it not filling the whole array with the last element?
What about:
int i=0;
for(Xml polh_is:fetchsite.child("site").child("poleis").children("polh")) { //url
if((polh_is.string("name")=="")||(polh_is.content()==""))//attribute
error += "Error in polh: name is - " + polh_is.string("name") + " with url - " + polh_is.content() + " -.\n";
else if (i >= citylink.length)
break;
else {
citylink[i][0]=HtmlMethods.removeBreaks(polh_is.string("name"));
citylink[i][1]=HtmlMethods.removeBreaks(polh_is.string("with url -"+polh_is.content() +"-.\n"));
i++;
}

Categories

Resources