I have a string which has numbers.
I have a code like this,
String tempStr = "+123";
NumberFormat numformat = NumberFormat.getNumberInstance();
numformat.setParseIntegerOnly(true);
try {
int ageInDays = Integer.parseInt(tempStr);
System.out.println("the age in days "+ageInDays);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It is working fine for the number with negative symbols.But I can't do it for number with '+' symbol. It throws NumberFormatException.
So how can I parse a number with '+' symbol from a string?
To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.
println("Write the character: "); String character = in. next(); if (chain. contains(character)) { cont = cont + 1; } System.
To parse a string in Java, you can use the Java String split() method, Java Scanner class, or StringUtils class. For parsing a string based on the specified condition, these methods use delimiters to split the string.
In the case you are using Java 7 or higher I would recommend using java.lang.Long; or java.lang.Integer; (if you are sure that you will have to parse integers).
It works for both cases.
Later edit: I didn't see that you were using Integer.parseInt();
Therefore I assume that you have Java 6 or less.
In this case try calling the following method before the line with Integer.parseInt(tempStr);
to remove the + in case it exists:
private static String removePlusSignIfExists(String numberAsString) {
if(numberAsString == null || numberAsString.length() == 0){
return numberAsString;
}
if(numberAsString.charAt(0) == '+'){
return numberAsString.substring(1, numberAsString.length());
} else {
return numberAsString;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With