Evaluating "IF ELSE" shorthand as part of a toString() Implementation [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have write the following toString() methode
public String toString() {
return "Product: "+ this.productName + ", Barcode: " + this.barCode
+ ", Expiration Date: " + this.expirationDate.toString() + ", Customer Price: "
+ this.customerPrice + ", Shops Price: " + this.shopsPrice
+ ", Instore Amount: " + this.inStoreAmount + ", Sale: "
+ (this.sale == null) ? "Not on sale" : + this.sale.toString();
}
But there is a problem with the way I use the if statement.
eclipse: "cannot covert from string to boolean"

You had an issue with the balancing of concatenation operator +. Also, I edited your method to be the following:
public String toString() {
return "Product: "+ this.productName + ", Barcode: " + this.barCode
+ ", Expiration Date: " + this.expirationDate.toString() + ", Customer Price: "
+ this.customerPrice + ", Shops Price: " + this.shopsPrice
+ ", Instore Amount: " + this.inStoreAmount + ", Sale: "+ ((this.sale == null) ? "Not on sale" : this.sale.toString());
}
When you are writing IF-ELSE short hand, try to keep everything in a (...) set of parentheses to keep track of things easily. I don't care what other professionals say about this, but if this helps you to understand things, so be it!

This is illegal syntax
(this.sale == null) ? "Not on sale" : + this.sale.toString()
and a compilation error should have alerted you to this problem.
Instead, use
((this.sale == null) ? "Not on sale" : this.sale.toString())
I've placed the entire ternary operator into parentheses to be clear.

Related

How to use RegEx in Java? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I would like to transfer the following code from Python to Java, but I get an error, while doing it:
import re
payload = re.search(
r'decrypt\.setPrivateKey\("(?P<privateKey>[^"]+)".*?'
r'decrypt\.decrypt\("(?P<cryptText>[^"]+)".*?'
r'document\.cookie="ipp_uid=(?P<ipp_uid>[^"]+)".*?'
r'document\.cookie="ipp_uid1=(?P<ipp_uid1>[^"]+)".*?'
r'document\.cookie="ipp_uid2=(?P<ipp_uid2>[^"]+)".*?'
r'url\s\+=\s"(?P<makeURL>.*?)"\;.*?'
r'salt="(?P<salt>[^"]+)"',
ret.content.decode('utf-8'),
re.MULTILINE | re.DOTALL
)
I have already tried the following code:
String patternString = "decrypt\\.setPrivateKey\\(\"(?P<privateKey>[^\"]+)\".*?\n"
+ " decrypt\\.decrypt\\(\"(?P<cryptText>[^\"]+)\".*?\n"
+ " document\\.cookie=\"ipp_uid=(?P<ipp_uid>[^\"]+)\".*?\n"
+ " document\\.cookie=\"ipp_uid1=(?P<ipp_uid1>[^\"]+)\".*?\n"
+ " document\\.cookie=\"ipp_uid2=(?P<ipp_uid2>[^\"]+)\".*?\n"
+ " url\\s\\+=\\s\"(?P<makeURL>.*?)\"\\;.*?\n"
+ " salt=\"(?P<salt>[^\"]+)\"";
Pattern payload = Pattern.compile(patternString);
String content = new String(html.getBytes(), "UTF-8");
Matcher m = payload.matcher(html);
if(m.find()){
System.out.println("Found: " + m.group(0));
}else{
System.out.println("not found");
}
... but I am getting this error:
java.util.regex.PatternSyntaxException: Unknown inline modifier near index 27
decrypt\.setPrivateKey\("(?P<privateKey>[^"]+)".*?
decrypt\.decrypt\("(?P<cryptText>[^"]+)".*?
document\.cookie="ipp_uid=(?P<ipp_uid>[^"]+)".*?
document\.cookie="ipp_uid1=(?P<ipp_uid1>[^"]+)".*?
document\.cookie="ipp_uid2=(?P<ipp_uid2>[^"]+)".*?
url\s\+=\s"(?P<makeURL>.*?)"\;.*?
salt="(?P<salt>[^"]+)"
^
at java.util.regex.Pattern.error(Pattern.java:1957)
at java.util.regex.Pattern.group0(Pattern.java:2896)
at java.util.regex.Pattern.sequence(Pattern.java:2053)
at java.util.regex.Pattern.expr(Pattern.java:1998)
at java.util.regex.Pattern.compile(Pattern.java:1698)
at java.util.regex.Pattern.<init>(Pattern.java:1351)
at java.util.regex.Pattern.compile(Pattern.java:1028)
at fabian.site.MyModule.test(MyModule.java:76)
at fabian.site.MyModule.run(MyModule.java:61)
at fabian.thread.ThreadPool$PoolThread.run(ThreadPool.java:50)
Thank you for your help guys!!
Two things stand out to me:
Named capturing groups in Java are structured like (?<name>X), not (?P<name>X), so you should remove the Ps
The names cannot contain "_", so you should replace ipp_uid with something like ippUid (only letters and numbers)
String patternString = "decrypt\\.setPrivateKey\\(\"(?<privateKey>[^\"]+)\".*?\n"
+ " decrypt\\.decrypt\\(\"(?<cryptText>[^\"]+)\".*?\n"
+ " document\\.cookie=\"ipp_uid=(?<ippuid>[^\"]+)\".*?\n"
+ " document\\.cookie=\"ipp_uid1=(?<ippuid1>[^\"]+)\".*?\n"
+ " document\\.cookie=\"ipp_uid2=(?<ippuid2>[^\"]+)\".*?\n"
+ " url\\s\\+=\\s\"(?<makeURL>.*?)\"\\;.*?\n"
+ " salt=\"(?<salt>[^\"]+)\"";
I don't have any sample data, so it's hard to tell whether it works this way, but it does compile without errors.

How do I concatenate strings in NETBEANS with + signs and escape codes?

Here's what I'm trying to do:
String output = "If you borrow" + currencyFormatter.format(loanAmount);
+" at an interest rate of" + rate + %;
+"\nfor" + years;
+",you will pay" + totalInterest + "in interest.";
Take out the semicolons before the end of your concatenation.
String output = "If you borrow" + currencyFormatter.format(loanAmount)
+" at an interest rate of" + rate + "%"
+"\nfor" + years
+",you will pay" + totalInterest + "in interest.";
I also recommend that you move the concatenation operator to the end of the line rather than the start of the line. It's a minor stylistic preference...
String output = "If you borrow" + currencyFormatter.format(loanAmount) +
" at an interest rate of" + rate + "%" +
"\nfor" + years +
",you will pay" + totalInterest + "in interest.";
Finally, you may notice that you are missing some white-spaces when you try printing that string. The String.format method helps with that (also see the documentation for Formatter). It's also faster than doing lots of concatenations.
String output = String.format(
"If you borrow %s at an interest rate of %d%%\nfor %d years, you will pay %d in interest.", currencyFormatter.format(loanAmount), rate, years, totalInterest
);

Calling a variable from other method [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 6 years ago.
I'm new to Java and this may be a basic question. It takes me long time to understand and hopefully someone will it to me. Why can't I put priceMessage at putExtra(Intent.EXTRA_TEXT ,....) ? Is there any possible way?
public String submitOrder (String name, int price, boolean addWhippedCream, boolean addChoc) {
String priceMessage = getString(R.string.price_symbol) + (calculatePrice(addWhippedCream, addChoc));
priceMessage += "\n" + getString(R.string.name_order) + name;
priceMessage += "\n" + getString(R.string.add_whipped_cream) + " (" + addWhippedCream +")";
priceMessage += "\n" + getString(R.string.add_chocolate) + " (" + addChoc + ")";
priceMessage += "\n" + getString(R.string.cup_of_coffee) + " : " + quantity + " " + getString(R.string.cup_of_coffee);
priceMessage += "\n" + getString(R.string.thank_you);
displayMessage(priceMessage);
return priceMessage;
}
/**
* Send Button Order for Intent Action
*/
public void sendOrder (View view){
EditText nameField = (EditText)findViewById(R.id. name_field);
String name = nameField.getText().toString();
Intent sendOrder = new Intent(Intent.ACTION_SENDTO);
sendOrder.setData(Uri.parse("mailto:"));
sendOrder.putExtra(Intent.EXTRA_SUBJECT,"Tempahan Kopi : " + name);
sendOrder.putExtra(Intent.EXTRA_TEXT,priceMessage);
startActivity(Intent.createChooser(sendOrder,"Hantar Tempahan"));
In Java (and many other Object-Oriented programming languages), variables defined in a method are only available inside that method. If you want to share variables between two different methods, you can pass them as method parameters, or create them as either static or instance class members.
I'd recommend checking out the official Java Trails Tutorials to help you get started with the language. It'll explain what the different types of variables are, and when you might want to use them.

Java NewLine "\n" not working in save to text file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is my code:
public String display() {
return "\n......................\nFixed Employee:\n" +
"Name: " + super.fullName() +
"\nSalary: " + salary() +
" tk\n......................";
}
But when I'm invoking this method from main class, "\n" newLine not working. just showing one line output. Will you plz help to solve the problem?
Thanks
For saving in files use \r\n. \n as new lines is viable on printstreams but not writing to files.
You may need the system independent line separator as it might differ from one OS to another. Just replace the \n with the value of line separator:
I can be retrieve as you load any system property:
public String display() {
String separator = System.getProperty("line.separator"); // Load the system property using its key.
return "\n......................\nFixed Employee:\n"
+ "Name: "
+ super.fullName() +
"\nSalary: "
+ salary()
+ " tk\n......................"
.replace("\\n", separator); // replace the \n before returning your String
}
Or simply use System#lineSeparator method as #Deepanshu Bedi suggested:
public String display() {
String separator = System.lineSeparator(); // Consider it as a shortcut.
return "\n......................\nFixed Employee:\n"
+ "Name: "
+ super.fullName() +
"\nSalary: "
+ salary()
+ " tk\n......................"
.replace("\\n", separator); // replace the \n before returning your String
}

What are some better ways to print the following section? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What are some better ways to print the following section? I think it will look better in a table format of some type with a heading. I want to adjust them to fixed lenghts, I think. Here is the code snippet I want to format to look better. The print elements are elements in a sql database.
System.out.println("\nAll records in your table:");
System.out.println("ID# Name GPA Status Mentor Level Thesis Advisor Company"); //table heading...
while (rs.next()) {
String output = " ";
output += rs.getString("studentID") + " "
+ rs.getString("firstName") + " "
+ rs.getString("lastName") + " "
+ rs.getString("gpa") + " "
+ rs.getString("status") + " "
+ rs.getString("mentor") + " "
+ rs.getString("level") + " "
+ rs.getString("thesisTitle") + " "
+ rs.getString("thesisAdvisor") + " "
+ rs.getString("company") + "\n";
System.out.printf("%s", output);
}
|You can|
|Do something|
|like this|
|studentname|
|firstname|
|middlename|
|.......|
"I want to adjust them to fixed lengths":
is that why your concatenating whitespaces in different lengths ?
You can try to concatenate "\t\t" instead.
In case it's HTML, using HTML Table will take care of it for you.

Categories