Getting A NumberFormat Exception in BlackBerry - java

I am trying to parse a string to int value. But i am getting a NumberFormat Exception. I am writing the below code:
Logger.out("Myprof", "Contact "+strContact);
try{
i = Integer.parseInt(strContact.trim());
Logger.out("Myprof", "Contact8686866 "+i);
}
catch(Exception e)
{
Logger.out("Myprof", "exce "+e.toString());
}
Now when i am passing like below:
i = Integer.parseInt("11223344");
I am getting the i value as 11223344.
Where i am doing wrong here? Please Help.

The input value of 9875566521 is greater than Integer.MAX_VALUE of 2147483647. Instead use a Long. (BigInteger not an option for Blackberry)
Long number = Long.parseLong(strContact);
Logger.out("Myprof", "Contact8686866 " + number);
If the intended input numbers are greater then Long.MAX_VALUE, then Character.iDigit can be used as an alternative to validate values:
private static boolean isValidNumber(String strContact) {
for (int i = 0; i < strContact.length(); i++) {
if (!Character.isDigit(strContact.charAt(i))) {
return false;
}
}
return true;
}

Related

Validating user input in arrays

Hey guys I am doing a project for school and am having a little trouble, I have a variable "reservationNumber" and im attempting to check if the number the user inputs is in the array, if not it returns a string saying the number was not found. It is working fine and displays the correct info when there is a valid input but when an invalid input is detected it gives a null.pointer.exception error. I tried writing it so that if the number is not detected the private method returns -1, then when I call the tickerInformation method, if that the variable 'ticket' returns -1 then it returns "invalid reservation number". This is where is error is being raised and only occurs when I enter an invalid number please help.
public void ticketInformation(String reservationNumber)
{
int ticket = searchArray(reservationNumber);
if (ticket == -1)
{
System.out.println("The reservation number entered was n0t found");
}
else
{
System.out.print("\n" + ticketSale[ticket].toString());
}
}
private int searchArray(String reservationNumber)
{
for (int i = 0; i < ticketSale.length; i++)
{
if (ticketSale[i].getReservationNumber().equals(reservationNumber))
{
return i;
}
}
return -1;
}
ticketSale[i].getReservationNumber().equals(reservationNumber) has an issue. Share the declaration and init for array "ticketSale". If ticketSale array is for abstract data type then why equal is called with String?
You didn't post the whole code but I think that when you enter invalid number as reservation number, it does not assigned to the related object's instance variable. So getReservationNumber() might be returning null.
Add a null check,
private int searchTicketSales(String reservationNumber) {
int reservationNumberIndex = -1;
for (int i = 0; i < ticketSale.length; i++) {
if (null != ticketSale[i].getReservationNumber() && ticketSale[i].getReservationNumber().equals(reservationNumber)) {
reservationNumberIndex = i;
break;
}
}
return reservationNumberIndex;
}
Best Regards,
Rakesh
Add a regex to validate that your input is a valid number "\\d+":
public void ticketInformation(String reservationNumber)
{
String regex = "\\d+";
if(!reservationNumber.matches(regex))
{
System.out.println("The reservation number entered was n0t found");
}
int ticket = searchArray(reservationNumber);
if(ticket == -1)
{
System.out.println("The reservation number entered was n0t found");
}
else
{
System.out.print("\n" + ticketSale[ticket].toString());
}
}
You might want to validate searchArray, particularly if it is not used interdependently from ticketInformation().

Convert String representation to minimal Number Object

Having a String representation of a number(no decimals), what's the best way to convert it to either one of java.lang.Integer or java.lang.Long or java.math.BigInteger? The only condition is that the converted type should be of minimal datatype required to hold the number.
I've this current implementation that works fine, but I would like to know if there's a better code without exception handling.
package com.stackoverflow.programmer;
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
String number = "-12121111111111111";
Number numberObject = null;
try {
numberObject = Integer.valueOf(number);
} catch (NumberFormatException nfe) {
System.out.println("Number will not fit into Integer type. Trying Long...");
try {
numberObject = Long.valueOf(number);
} catch (NumberFormatException nfeb) {
System.out.println("Number will not fit into Long type. Trying BigInteger...");
numberObject = new BigInteger(number);
}
}
System.out.println(numberObject.getClass() + " : "
+ numberObject.toString());
}
}
From what you said, here is what I would have done:
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
public class TestSO09_39463168_StringToMinimalNumber {
public static void main(String[] args) {
List<String> strNumbers = Arrays.asList("0", //int
"123", //int
"-456", //int
"2147483700", // Long
"-2147483700", // Long
"9223372036854775900", //BigInt
"-9223372036854775900" //BigInt
);
for(String strNumber : strNumbers){
Number number = stringToMinimalNumber(strNumber);
System.out.println("The string '"+strNumber+"' is a "+number.getClass());
}
}
public static Number stringToMinimalNumber(String s){
BigInteger tempNumber = new BigInteger(s);
if(tempNumber.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 || tempNumber.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0){
return tempNumber;
} else if(tempNumber.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0 || tempNumber.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0){
return tempNumber.longValue(); //Autobox to Long
} else {
return tempNumber.intValue(); //Autobox to Integer
}
}
}
You must use a temporary BigInteger, or else you'll end up with lazarov's solution, which is correct, but you can't really do something like that for reason mentionned in the comments.
Anyway, every BigInteger (the ones that are not returned) will be garbage collected. As for autoboxing, I don't think it's that of a bad thing. You could also make "BigInteger.valueOf(Long.MAX_VALUE))" as a constant. Maybe the compiler or the JVM will do this on its own.
I'm not really sure of how efficient it is, and using only BigInteger might be a good idea (as Spotted did), because I serioulsy doubt it would really improve the rest of your code to use the right size, and it might even be error prone if you try to use these Numbers with each other ... But again, it all depend on what you need. (and yes, using Exception as flow control is a really bad idea, but you can add a try catch on the BigInteger tempNumber = new BigInteger(s); to throw your own exception if s is not a number at all)
For recreational purpose, I have made the solution without using a BigInteger, and only with String parsing (this is still not what I recommand to do, but it was fun :)
public static final String INT_MAX_VALUE = "2147483647";
public static final String LONG_MAX_VALUE = "9223372036854775807";
public static Number stringToMinimalNumberWithoutBigInteger(String numberStr){
//Removing the minus sign to test the value
String s = (numberStr.startsWith("-") ? numberStr.substring(1,numberStr.length()) : numberStr);
if(compareStringNumber(s, LONG_MAX_VALUE) > 0){
return new BigInteger(numberStr);
} else if(compareStringNumber(s, INT_MAX_VALUE) > 0){
return new Long(numberStr);
} else {
return new Integer(numberStr);
}
}
//return postive if a > b, negative if a < b, 0 if equals;
private static int compareStringNumber(String a, String b){
if(a.length() != b.length()){
return a.length() - b.length();
}
for(int i = 0; i < a.length(); i++){
if( a.codePointAt(i) != b.codePointAt(i) ){ //Or charAt()
return a.codePointAt(i) - b.codePointAt(i);
}
}
return 0;
}
Please don't use exceptions for handling flow control, this is a serious anti-pattern (also here).
As you mentionned in the comments, the real thing you've been asked is to convert a List<String> into a List<Number>.
Also, if I understand correctly, you know that:
You should encounter only numbers without decimals
The biggest value you can encounter is possibly unbound
Based on that, the following method will do the job in a more clever way:
private static List<Number> toNumbers(List<String> strings) {
return strings.stream()
.map(BigInteger::new)
.collect(Collectors.toList());
}
Eidt: if you're not very familiar with the stream concept, here's the equivalent code without streams:
private static List<Number> toNumbers(List<String> strings) {
List<Number> numbers = new ArrayList<>();
for (String s : strings) {
numbers.add(new BigInteger(s));
}
return numbers;
}
Well if you want to do it "by hand" try something like this:
We define the max values as strings :
String intMax = "2147483647";
String longMax = "9223372036854775807";
and our number:
String ourNumber = "1234567890"
Now our logic will be simple :
We will check lenghts of strings firstly
If our numbers length < int max length : IT IS INT
If our numbers length == int max length : Check is it INT or LONG
If our numbers length > int max length :
3.1 If our numbers length < long max length : IT IS LONG
3.2 If our numbers length == long max length : Check is it LONG or BIG INTEGER
3.3 If our numbers length > long max length : IT IS BIG INTEGER
The code should look something like this (I have not tried to compile it may have syntax or other errors) :
if(ourNumber.lenght() < intMax.length ){
System.out.println("It is an Integer");
} else if(ourNumber.lenght() == intMax.length){
// it can be int if the number is between 2000000000 and 2147483647
char[] ourNumberToCharArray = ourNumber.toCharArray();
char[] intMaxToCharArray = intMax.toCharArray();
int diff = 0;
for(int i = 0; i < ourNumberToCharArray.length; i++) {
diff = Character.getNumericValue(intMaxToCharArray[i]) - Character.getNumericValue(ourNumberToCharArray[i]);
if(diff > 0) {
System.out.println("It is a Long");
break;
} else if(diff < 0) {
System.out.println("It is an Integer");
break;
}
}
if(diff == 0){
System.out.println("It is an Integer");
}
} else {
if(ourNumber.lenght() < longMax.length()) {
System.out.println("It is a Long");
} else if(ourNumber.lenght() == longMax.length()){
char[] ourNumberToCharArray = ourNumber.toCharArray();
char[] longMaxToCharArray = longMax.toCharArray();
int diff = 0;
for(int i = 0; i < ourNumberToCharArray.length; i++) {
diff = Character.getNumericValue(longMaxToCharArray[i]) - Character.getNumericValue(ourNumberToCharArray[i]);
if(diff > 0) {
System.out.println("It is a BigInteger");
break;
} else if(diff < 0) {
System.out.println("It is a Long");
break;
}
}
if(diff == 0){
System.out.println("It is a Long");
}
} else {
System.out.println("It is a BigInteger");
}
}
Then logic that checks if the numbers match or not is the same in both cases you can but it in a function for example.

Retrieving Unknown Value using Jsoup

I'm attempting to pull the 'Total Cash Flow From Operating Activities' figure from Yahoo Finance. The variable "s" can be any symbol in the SP500. For the most part, the desired output occurs. However, in some cases, like for AAPL, I can't figure out what it's printing or where it came from.
If "s" is A, the output is 711000000. Correct.
If "s" is AA, the output is 1674000000. Correct.
However, if "s" is AAPL, the output is -416542144. No clue where that comes from.
public class CashFlowStatement {
String cashFromOperatingActivities = "Total Cash Flow From Operating Activities";
public CashFlowStatement(String s) {
String cashFlowStatementURL = ("https://finance.yahoo.com/q/cf?s="+s+"+Cash+Flow&annual");
String cashFlowStatementTableName = "table.yfnc_tabledata1";
boolean foundLine = false;
String line;
int line2;
try {
Document doc = Jsoup.connect(cashFlowStatementURL).get();
for (Element table : doc.select(cashFlowStatementTableName)) {
for (Element row : table.select("tr")) {
if(foundLine == false) {
Elements tds = row.select("td");
for( int j = 0; j < tds.size() - 1; j++) {
if(tds.get(j).text().equals(cashFromOperatingActivities)) {
line = tds.get(j+1).text().replaceAll(",","");
line = line.substring(0,(line.length())-2);
line2 = Integer.parseInt(line)*1000;
System.out.println(line2);
foundLine = true;
}
}
}
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (NumberFormatException ex) {
ex.printStackTrace();
}
}
}
You have an OVERFLOW! The value from the table is 59,713,000. When you multiply it by 1000 - line2 = Integer.parseInt(line)*1000; you get a number which is greater than MAXINT, thus the negative value. Try use long instead int for line2.

counting unique combinations of object properties

I have a class TypesHolder that has four properties which are each int values. I want to identify how many unique combinations of values are in the four int variables, and then to give a count of how many instances of TypesHolder have each specific combination of the four integer variables. How can I accomplish this in code? My code attempt below is failing, with the failed results summarized at the end. There must be a simpler way to do this correctly.
Here is my TypesHolder class:
public class TypesHolder {
private int with;
private int type;
private int reason1;
private int reason2;
//getters and setters
}
To hold the unique combinations during analysis, I created the following TypesSummaryHolder class:
public class TypesSummaryHolder {
private int with;
private int type;
private int reason1;
private int reason2;
private int count;
//getters and setters
}
I then created an ArrayList to store the 15000+ instances of TypesHolder and another ArrayList to store the TypesSummaryHolder objects who represent each of the unique combinations of width, type, reason1, and reason2 from the TypesHolder objects, along with a count variable for each of the unique combinations. I wrote the following code to populate the ArrayList of TypesSummaryHolder objects along with their counts:
#SuppressWarnings("null")
static void countCommunicationTypes(){
int CommunicationWithNumber;int CommunicationTypeNumber;int CommunicationReasonNumber;
int SecondReasonNumber;int counter = 0;
ArrayList<EncounterTypesHolder> types = new ArrayList<EncounterTypesHolder>();
ArrayList<EncounterTypesSummaryHolder> summaries = new ArrayList<EncounterTypesSummaryHolder>();
////////
try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}
catch (ClassNotFoundException e1) {e1.printStackTrace();}
Connection sourceConn = null;
try {sourceConn = DriverManager.getConnection("jdbc:odbc:PIC_NEW_32");}
catch (Exception e1) {e1.printStackTrace();}
Statement st = null;
try {st = sourceConn.createStatement();}
catch (Exception e1) { e1.printStackTrace();}
ResultSet rest = null;
try {
rest = st.executeQuery("SELECT * FROM someTable");
while (rest.next()) {
CommunicationWithNumber = rest.getInt(3);
CommunicationTypeNumber = rest.getInt(5);
CommunicationReasonNumber = rest.getInt(6);
SecondReasonNumber = rest.getInt(6);
EncounterTypesHolder etype = new EncounterTypesHolder();
etype.setWith(CommunicationWithNumber);
etype.setType(CommunicationTypeNumber);
etype.setReason1(CommunicationReasonNumber);
etype.setReason2(SecondReasonNumber);
if(!isDuplicateType(etype,types)){
EncounterTypesSummaryHolder summaryholder = new EncounterTypesSummaryHolder();
summaryholder.setWith(CommunicationWithNumber);
summaryholder.setType(CommunicationTypeNumber);
summaryholder.setReason1(CommunicationReasonNumber);
summaryholder.setReason2(SecondReasonNumber);
summaryholder.setCount(1);
summaries.add(summaryholder);
} else {
EncounterTypesSummaryHolder summaryholder = new EncounterTypesSummaryHolder();
summaryholder.setWith(etype.getWith());
summaryholder.setType(etype.getType());
summaryholder.setReason1(etype.getReason1());
summaryholder.setReason2(etype.getReason2());
if(isDuplicateSummaryType(summaryholder, summaries)){
for(int u = 0; u<summaries.size();u++){
if((CommunicationWithNumber==summaries.get(u).getWith()) && (CommunicationTypeNumber==summaries.get(u).getType()) && (CommunicationReasonNumber==summaries.get(u).getReason1()) && (SecondReasonNumber==summaries.get(u).getReason2()) ){
int oldcount = summaries.get(u).getCount();
int newcount = oldcount+1;
summaries.get(u).setCount(newcount);
}
}
}else {
summaryholder.setCount(1);
summaries.add(summaryholder);
}
}
types.add(etype);
counter += 1;
System.out.println("counter is: "+counter);
System.out.println("summaries.size() is: "+summaries.size());
}
} catch (Exception e) {e.printStackTrace();}
System.out.println("at end: counter is: "+counter);
System.out.println("at end: types.size() is: "+types.size());
System.out.println("at end: summaries.size() is: "+summaries.size());
int total = 0;
for(int r=0;r<summaries.size();r++){
total += summaries.get(r).getCount();
int with = summaries.get(r).getWith();int type = summaries.get(r).getType();int reason1 = summaries.get(r).getReason1();int reason2 = summaries.get(r).getReason2();int thiscount = summaries.get(r).getCount();
}
System.out.println("total is: "+total);
}
static boolean isDuplicateType(EncounterTypesHolder testType, ArrayList<EncounterTypesHolder> types){
for(int j = 0; j<types.size(); j++){
if( (testType.getWith() == types.get(j).getWith()) && (testType.getType() == types.get(j).getType()) && (testType.getReason1() == types.get(j).getReason1()) && (testType.getReason2() == types.get(j).getReason2())){
System.out.println("=====TRUE!!====");
return true;
}
}
return false;
}
static boolean isDuplicateSummaryType(EncounterTypesSummaryHolder testType, ArrayList<EncounterTypesSummaryHolder> types){
for(int j = 0; j<types.size(); j++){
if( (testType.getWith() == types.get(j).getWith()) && (testType.getType() == types.get(j).getType()) && (testType.getReason1() == types.get(j).getReason1()) && (testType.getReason2() == types.get(j).getReason2())){
System.out.println("=====TRUE!!====");
return true;
}
}
return false;
}
The code above is producing the following SYSO output at the end:
at end: counter is: 15415
at end: types.size() is: 15415
at end: summaries.size() is: 15084
total is: 2343089
The max possible value for summaries.size() should be around 600, but the 331 you get from types.size() minus summaries.size() above is within the range of believable values for summaries.size(). However, the value for total should be equal to the 15414 value of types.size(). What is wrong with my code above? How can I change my code above to get both a list of the unique combinations of with, type, reason1, and reason2, and also a count of the number of instances with each of those unique value combinations?
If I understand you right, you could add hashcode() and equals() methods to to TypesHolder, then add all your values to a Set<TypesHolder> of some sort. Then just count the total objects (call size()) in the set to get the number of unique combinations.
Here's a link to implementing hashcode() and equals() from SO, if you're not familiar with those methods. Google is your friend.

Validating int and float value all together

I am getting a value named amount in an object through its getter as shown below.
Let's say the object is h then
h.getAmount()
Now I need to develop a validator that will validate that amount should be of type integer and if it is not then it will throw the exception, I have developed that also as shown below
private boolean isint (String amount){
boolean isValid = true;
try {
Integer.parseInt(amount);
}
catch(NumberFormatException e){
isValid = false;
}
return isValid;
}
Now the issue is that amount coming from h is an integer such as 1234, but it can also be a float such as 1258.26. So in the case of float it throws a NumberFormatException.
How could I make it perfect for both the values whether it is integer or whether it is float?
You could use a regex like this:-
if (str.matches("[-+]?[0-9]*\\.?[0-9]+")) { // You can use the `\\d` instead of `0-9` too!
// Is a number - int, float, double
}
[-+]? - For the sign.
[0-9]*\.?[0-9]+ - For the numbers and the decimal point between them.
Update:-
In case exponential needs to be handled too, then the below regex can be used.
String regex = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?";
First of all, if you have a function called isInt it should do exactly that -- check if it's an integer. No more and no less.
You could try something like that
enum VarType {
INTEGER, FLOAT, STRING, EMPTY
}
private VarType getVarType(String amount){
if (amount.length() ==0) {
return VarType.EMPTY;
}
if (amount.contains(".")) {
try {
Float.parseFloat(amount);
}
catch(NumberFormatException e){
return ValType.STRING;
}
return ValType.FLOAT;
} else {
try {
Integer.parseInt(amount);
}
catch(NumberFormatException e){
return ValType.STRING;
}
return ValType.INTEGER;
}
}
I would not recommend it though, because using exceptions in this way is really expensive. Exceptions should be used as their name suggests, to handle special cases, exceptions, and not as a standard flow.
I would do it like this:
public class ParseVarTest {
static enum VarType {
INTEGER, FLOAT, STRING, EMPTY
}
private static VarType getVarType(String amount){
boolean onlyDigits = true;
int dotCount = 0;
if (amount == null) {
return VarType.EMPTY;
}
String trimmed = amount.trim();
if (trimmed.length() == 0) {
return VarType.EMPTY;
}
int a=0;
if (trimmed.charAt(0) == '-') {
a++;
}
for (int max=trimmed.length(); a<max; a++) {
if ( trimmed.charAt(a) == '.' ) {
dotCount++;
if (dotCount>1) break;
} else if ( !Character.isDigit(trimmed.charAt(a)) ) {
onlyDigits = false;
break;
}
}
if (onlyDigits) {
if (dotCount ==0) {
return VarType.INTEGER;
} else if (dotCount ==1) {
return VarType.FLOAT;
} else {
return VarType.STRING;
}
}
return VarType.STRING;
}
public static void main(String[] args) {
String[] vars = {"", " ", "123", "-5123", "1234.41", "-1234.41", "-1234..41","a12312", "523sdf234sdf.123"};
for (String var: vars) {
System.out.print(var);
System.out.print(": \t");
System.out.println(getVarType(var));
}
}
}
It's quite long for such a simple task, but:
no regexes
at most a single scan of the string
readable (IMO)
fast
However, this solution does not validate the range of the value. String 10000000000 would still be recognized as a VarType.INTEGER even though the value could not fit into an int variable in Java.
Use Double.parseDouble ... (method name changed to isNumber to better reflect the meaning of the method) ...
private boolean isNumber (String amount){
boolean isValid = true;
try {
Double.parseDouble(amount);
}
catch(NumberFormatException e){
isValid = false;
}
return isValid;
}
... and could simplify to ...
private boolean isNumber (String amount){
try {
Double.parseDouble(amount);
}
catch(NumberFormatException e){
return false;
}
return true;
}
As suggested, it would be better to use long and double instead of int and float.
By the way, can't you simply check for a float ? If it is an int, than it can always be a float, potentially rounded with loss of precision.
public static boolean isFloat(String number){
try {
return !new Float(number).isNaN();
} catch (NumberFormatException e){
return false;
}
}
Running demo: https://ideone.com/UpGPsK
Output:
> 1234 IS a valid Integer or Float
> 1234.56 IS a valid Integer or Float
> 1234.56.78 IS NOT a valid Integer or Float
> abc IS NOT a valid Integer or Float
> 2147483647 IS a valid Integer or Float
> 3.4028235E38 IS a valid Integer or Float
> -2147483648 IS a valid Integer or Float
> 1.4E-45 IS a valid Integer or Float
If you're talking about integers or a few decimals, you're probably talking about money or quantities, for which BigDecimal is ideal; and floating-point not really so good (due to rounding errors).
Otherwise, you're talking about a double floating-point value.
new BigDecimal( str) will parse an integer or decimal for you, but it will also accept exponents; eg 1.4E2 means 140.
Perhaps you want to use a regex pattern to validate it first;
if (! str.matches( "[-+]?(\\d+)|(\\d*\\.\\d+)"))
throw new NumberFormatException();
This pattern accepts decimals without any leading digits, such as .14159 -- which should be allowable.

Categories

Resources