com.ibm.icu.text.DecimalFormat always throws ParseException - java

With the following code I only want to allow positive numbers. For some reason i am not even able to parse the strings correctly:
DecimalFormat dfNoNegative = new DecimalFormat("#,##0.00");
dfNoNegative.setNegativePrefix("");
try {
System.out.println(dfNoNegative.parse("123.00"));
} catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println(e.getErrorOffset());
e.printStackTrace();
}
Error message and ErrorOffset:
Unparseable number: "123.00"
6
Can anyone guide me where I am mistaken? An example for a working String would be good as well

My mistake was to dfNoNegative.setNegativePrefix(""); to nothing (""). This doesn't work, because the String started directly with the number and 123 is not "", and therefore it fails. Basically this method overwrites what should be used as negative prefix (default is -). If you set it to ! as example, System.out.println(dfNoNegative.parse("!123.00")); would print -123.

Related

getting detail country name and country code of a given phone number

I able to detect incoming calls in android but problem is that I want to know to the country code of that phone number so that I can analyze whether it is a national or international number. I know about libphonenumber
but It needs to know region code before hand to get the country code as shown in the example
String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
it already knows to put "CH" as a parameter. but we don't know if the number is to known to us then how we can analyze that number.
As long as it is not a regional number (in which case it is just a plain number and no lib in this world could determine where it is from) you can specify "ZZ" or null for the second parameter of parse.
This is what the documentation says:
region that we are expecting the number to be from. This is only used
if the number being parsed is not written in international format. The
country_code for the number in this case would be stored as that of
the default region supplied. If the number is guaranteed to start with
a '+' followed by the country calling code, then "ZZ" or null can be
supplied.
After you where able to create an instace of PhoneNumber you can simply call getRegionCodeForNumber as shown below.
String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber numberProto = phoneUtil.parse(swissNumberStr, "ZZ");
System.out.println(phoneUtil.getRegionCodeForNumber(numberProto));
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}

Using Java Desktop mailto for two recipients

I am trying to add a feedback button to a Java program for work. I want this button to actually send an email to myself and one other person. All employees have the same default email application so using the Desktop mail method works fine.
I managed to get this working with 1 email addressee. It properly opens the email client, starts a new email and puts the addressee in the address line. The problem is when I try to add two email addresses.
int result = JOptionPane.showOptionDialog(null, panel, "Feedback", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, options1, null);
if(result == JOptionPane.NO_OPTION){
try {
Desktop.getDesktop().mail(new URI("mailto:Chuck.Norris#yahoo.com"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So doing it like that works perfectly.
I've tried simply separating the addresses with a comma like this:
Desktop.getDesktop().mail(new URI("mailto:Chuck.Norris#yahoo.com","Bill.Clinton#gmail.com"));
but this gives me an error and the only option is to actually remove the second argument.
Finally I've tried using a String[] like this:
String[] mailAddressTo = {"Chuck.Norris#yahoo.com","Bill.Clinton#gmail.com"};
and then inserting that into the mailto method like this:
Desktop.getDesktop().mail(new URI("mailto:"+mailAddressTo));
but the email address comes out being
[Ljava.lang.String; #5e9394f7
once the email client is opened.
I've tried searching online and while I did find some solutions in regards to sending mail using Java through other methods than Desktop.mail - I found nothing related to how to accomplish this with Desktop.
If anyone can let me know how to make this work I would greatly appreciate it!
It helps to look at the documentation instead of guessing.
The list of URI constructors shows that there is no URI constructor which takes two Strings. That is why your first approach failed.
In Java, all arrays extend Object and inherit the default toString method of Object. Concatenating objects with + automatically invokes each object’s toString method, which is why your second approach yielded the results it did.
The official definition of the format of mailto: URLs is RFC 2368, which states that multiple recipients can be specified by separating with commas. So, you were on the right track.
As of Java 8, you can simply join your addresses with String.join:
String[] mailAddressTo = {"Chuck.Norris#yahoo.com","Bill.Clinton#gmail.com"};
Desktop.getDesktop().mail(new URI("mailto:" + String.join(",", mailAddressTo)));
However, the documentation of the URI class states that the single-argument constructor assumes its String argument is already properly escaped. While it’s true that the example e-mail addresses you’ve provided don’t need to be escaped, it’s not safe to make that assumption with all possible addresses. To deal with this, you can use a multiple-argument URI constructor that will do the correct URI-escaping for you:
String[] mailAddressTo = { "Chuck.Norris#yahoo.com", "Bill.Clinton#gmail.com" };
Desktop.getDesktop().mail(new URI("mailto", String.join(",", mailAddressTo), null));
If you’re using a version of Java older than 8, you can build the string yourself:
String[] mailAddressTo = { "Chuck.Norris#yahoo.com", "Bill.Clinton#gmail.com" };
StringBuilder addressList = new StringBuilder();
String separator = "";
for (String address : mailAddressTo) {
addressList.append(separator).append(address);
separator = ",";
}
Desktop.getDesktop().mail(new URI("mailto", addressList.toString(), null));

Error NumberFormatException on Java

I have the following exception trying to manipulate a value to be added;
thank you very much for your help
java.lang.NumberFormatException: Invalid double: "20,000"
java.lang.StringToReal.invalidReal(StringToReal.java:63)
java.lang.StringToReal.parseDouble(StringToReal.java:269)
java.lang.Double.parseDouble(Double.java:295)
java.lang.Double.valueOf(Double.java:332)
You can use a NumberFormat to parse your String1. Something like,
String str = "20,000";
NumberFormat nf = NumberFormat.getNumberInstance(new Locale("en_US"));
NumberFormat nfIT = NumberFormat.getNumberInstance(Locale.ITALIAN);
try {
System.out.println(nf.parse(str)); // <-- 20000
System.out.println(nfIT.parse(str)); // <-- 20
} catch (ParseException e) {
e.printStackTrace();
}
For more options see Customizing Formats (The Java Tutorials).
1Being sure to pass the appropriate Locale to match your expected output.
You don't use comma as a separator in numbers.
You have to use 20000 instead of 20,000.
EDIT:
as #MitchWeaver mentioned, you can also substitute comma to underescore, making it 20_000

Java Style: Catching a bunch of slightly different errors

In a program I'm working on in Java where I have to read data from a file. The data is formatted so that each line contains all the necessary information to construct a new object. When I parse the data, I have a block of code that looks something like this:
String[] parts = file.nextLine().split(",");
String attr1 = parts[0];
int attr2, attr3;
try{
attr2 = Integer.parseInt(parts[1]);
} catch (NumberFormatException ex){
System.out.println("Could not parse attr2, got " + parts[1] + ".");
return;
}
try{
attr3 = Integer.parseInt(parts[2]);
} catch (NumberFormatException ex){
System.out.println("Could not parse attr3, got " + parts[2] + ".");
return;
}
ClassA attr4 = null, attr5 = null, attr6 = null;
try{
...
} catch (SomeExceptionType ex){
System.out.println("Could not parse attr4, got " + parts[3] + ".");
}
...
I find myself repeating the same simple try block over and over again. In an attempt to mitigate the situation and adhere to the DRY principle a bit more, I introduced some attempt methods:
int attr2 = attemptGetInt(parts, 1, "attr2");
int attr3 = attemptGetInt(parts, 2, "attr3");
ClassA attr4 = attemptGetClassA(parts, 3, "attr4");
...
// Somewhere in the class
public int attemptGetInt(String[] parts, int index, String name) throws SomeOtherException1{
try{
return Integer.parseInt(parts[index]);
} catch (NumberFormatException ex){
throw new SomeOtherException1("Could not parse " + name + ", got " + parts[index] + ".");
}
}
public ClassA attemptGetClassA(String[] parts, int index, String name) throws SomeOtherException2{
try{
return ...
} catch (SomeExceptionType ex){
throw new SomeOtherException2("Could not parse " + name + ", got" + parts[index] + ".");
}
}
...
Even this feels weird though, because there are a lot of different types I have to return that all sort of have the same but slightly different code and need to catch a slightly different error each time (i.e. I have to create an attemptGetClassB and attemptGetClassC and so on, a bunch of times with similar code each time).
Is there an elegant way of writing code like this?
If you have control over the format of the input file you might wish to change it to XML with a schema. That way the parser itself takes care of a lot of this type of checking for you.
However from the nature of the question I assume the format is fixed. In that case I would suggest splitting the syntax checking and parsing into separate steps for each line.
An easy way to do the syntax checking is using a regexp. Fairly complex syntax can be encoded in a regular expression so unless the files contain some sort of nesting (in which case DEFINITELY use XML instead) then it should be fairly straightforward.
The second step of parsing should then only return exceptions by exception :-) You still need to catch them but it's perfectly good form to gather all of your catches into a single block because it should only be used when debugging: in normal operations the syntax check will catch errors before this step.
My view is that this design is more intuitive and obvious. It may have a downside in error reporting if you specifically want to report on each error separately. In that case you'll need to break the string into substrings first (using a Scanner for example) and then syntax check each substring.
As a final note, opinions vary on this but my personal preference is not to use exception handling for conditions that occur in normal operations. They are not well suited for that (in my opinion). Better to do what I'm suggesting here: have explicit code to check error conditions before processing and then use exceptions for things that should not normally occur.

Strange error with Prepared query is not of type SELECT_LONG

I want to ask how can I make queries for this. I want to check the name from edit text and if the name exsist, as a part of record, in db i want to fill all edit texts with data from this object. Also I've got very strange error. Please help or give me an advice how to start with it. Im beginner. Thanks for all answers and clues.
Here is my code:
if(et_nazwa!=null){
long value = 0;
try {
PreparedQuery<Klient> query = klientDao.queryBuilder()
.where().eq("Kli_nazwa",et_nazwa.getText().toString()).prepare();
value = klientDao.countOf(query);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(value!=0){
PreparedQuery<Klient> q_adres = klientDao.queryBuilder().selectColumns("Kli_adres").where().eq("Kli_nazwa",et_nazwa.getText().toString()).prepare();
PreparedQuery<Klient> q_nip = klientDao.queryBuilder().selectColumns("Kli_nip").where().eq("Kli_nazwa",et_nazwa.getText().toString()).prepare();
et_adres.setText(q_adres.toString());
et_nip.setText(q_nip.toString());
}
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I've got this strange error like:
java.lang.IllegalArgumentException: Prepared query is not of type SELECT_LONG, did you call QueryBuilder.setCountOf(true)?
java.lang.IllegalArgumentException: Prepared query is not of type SELECT_LONG, did you call QueryBuilder.setCountOf(true)?
So the exception is trying to tell you what went wrong. When you build a query, ORMLite does not know what the query is going to be used for. Because you can select various columns and the like or use aggregate functions (like MAX(...)) it records an internal query-type and then checks it when the query is executed.
If you want to use Dao.countOf(...) then you need to add setCountOf(true) on your QueryBuilder object. The docs for Dao.countOf(...) should be made more explicit of this fact.
PreparedQuery<Klient> query = klientDao.queryBuilder().setCountOf(true)
.where().eq("Kli_nazwa",et_nazwa.getText().toString()).prepare();
If you use queryBuilder.countOf() or where.countOf() then it will set the count-of flag internally. You can get the count of the query without this problem by doing:
value = klientDao.queryBuilder()
.where().eq("Kli_nazwa",et_nazwa.getText().toString()).countOf();
Btw, this is a strange pattern:
et_adres.setText(((PreparedQuery)q_adres).toString());
Maybe you wanted to do the following?
String queryString = klientDao.queryBuilder()...prepareStatementString();

Categories