Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1109
  • Last Modified:

check a string value (convert to decimal) for greater or equal to zero in java

Hi
I am new to Java and JDeveloper and I am trying to debug and add custom code to one of the java files in JDeveloper to check a string value (TotalAmt) to be greater or equal to zero - if it is then I need to post a warning message as the value cannot be greater than zero - how do I do this? I googled but nothing really helped - I tried something like this

if (row.getTotalamt() > 0 ) { String message = "Total  Amount Cannot be Positive!";
        throw new OAException(message, OAException.ERROR); }
But I got following error in compilation
Error(581,26): method >(java.lang.String, int) not found in class appl.oracle.apps.custom.schema.server.MyReqAMImpl

Let me know -
0
mahjag
Asked:
mahjag
  • 25
  • 14
  • 3
  • +1
1 Solution
 
for_yanCommented:

float f = 1;
try{
 f = Float.parseFloat(row.getTotalAmt());
} catch (Exception ex) {


System.out.println("Total Amount is not a number");;
throw new Exception("Total amount is not a numbe");
}

if(f > 0) {
System.out.println("Total Amount is positive");;

throw new Exception("Positive amount");

}
0
 
for_yanCommented:
somethid like above - in fact you row.getTotalAmount() returns a String - you have to convert it to a number - Float.parseFloat ()
method will do it for you, but you should also take care of possible error where the string will have non-numeric chracters where it cannot be converted to number
0
 
mahjagAuthor Commented:
Thanks For Yan

I applied the code - got the following error in compilation

Error(582,1): unreported exception: java.lang.Exception; must be caught or declared to be thrown from the below code

try{
 f = Float.parseFloat(row.getTotalAmt());
} catch (Exception ex) {


System.out.println("Total Amount is not a number");;
throw new Exception("Total amount is not a numbe");
}

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
for_yanCommented:
Of course if you use throw Exception(..)
inside your method , then in the method declaration you should say

public void method_name(arguments) throws Exception....

and in  the code where you invoike this method
it will asjk you to enclose the call into try catch braces
- that is the main point of throwing execption
0
 
mahjagAuthor Commented:
not sure what should I do after your post - sorry
0
 
for_yanCommented:
why do you want to throw exception?

You probably rather want to print it to use either
with System.out.println("Total amount cann not be piositive")
or pop-up error message something like that


Exception is only useful if youy have another part of the software whoich knows what to do with that exception,
otherwise yiou just want to communicate the errort to the user


0
 
for_yanCommented:
So if you have a metyhod inside which you use
operator

"throw new Exception..." then you should declare it in the declaration of the method like here:

public class MyClass{

public void method() throws Exception {

//some code here where as smoe point it says throw new Exception(..);


}

}

Open in new window



and in anoyther peiece of code where you call this method
compile will require that you catch te exeception like

//some code
MyClass mc = new MyClass();


try{
mc.method();
} catch(exception ex){

System.out.println("there was an execpetion");
ex.printStacktrace();

}

Open in new window


If the method throws exception compiler woll not allow you to compile
the call to this method unles you enclose it into
try-catch
loop

So this "throw Exception" allows you to defer the
error message to the calling method call rather than to deal with the error on the spot, which is somethimes useful
(especially if dofferent parts of software are writtemn by sifferent people),
 but simetimes you may be better off just reporting the error to the user
rather than throwing and exception

0
 
CEHJCommented:
Make that instead
throw new RuntimeException("Total amount is not a number");

Open in new window

0
 
mahjagAuthor Commented:
Hi For Yan and CEHJ

Thanks for your posts -

I  was able to compile the code after I commented the sections it was complaining on - but have run time issues -
oracle.apps.fnd.framework.OAException: java.lang.NumberFormatException: For input string: "200,000.00"

This was caused when I got the Total amount as positive and the value being 200000.00 - not sure why it would throw a format exception - any ideas?
0
 
for_yanCommented:
Becuase it has a comma inside - nummbers in Java should not have commas
0
 
for_yanCommented:

You can run this method on your strinfg before you do parse

 Float.parseFloat(row.getTotalAmt().replace(",",""));
it should replace "," with nothing
0
 
mahjagAuthor Commented:
Again Thanks a lot for your quick postings For Yan -

I got compilation error after adding the above code

Error(577,43): method replace(java.lang.String, java.lang.String) not found in class java.lang.String
0
 
for_yanCommented:
then try replaceAll(",","") instead of reaplace(",","')
0
 
for_yanCommented:
Which version of Java are you using?

I guess Java 6 should have replace(String, String)

But replaceAll should work form Java 1.4 and in this acse it should work the same way
0
 
for_yanCommented:

yes,  replaceAll(",","") does  work the same; I checked it:
    System.out.println("2,000,000.00".replaceAll(",",""));

Open in new window


2000000.00

Open in new window

0
 
mahjagAuthor Commented:
Thanks again for your posts - above code compiled and now it worked for the numbers that are greater than zero - but did not work for the Total Amount value being negative (which is the correct test case). got the same error  - oracle.apps.fnd.framework.OAException: java.lang.NumberFormatException: For input string: "200,000.00"

I only added code for value greater than zero - if it is less than zero the application should work - not sure why it did not -

0
 
for_yanCommented:
But it again shows this string with comma inside like bfoe - did you use replace() - ?
0
 
for_yanCommented:

Add printout before the parsing:
float f = 1;
try{
System.out.println("before parsing; " + row.getTotalAmt().replaceAll(",","");

 f = Float.parseFloat(row.getTotalAmt().replaceAll(",","'));
} catch (Exception ex) {


System.out.println("Total Amount is not a number");;
throw new Exception("Total amount is not a numbe");
}

if(f > 0) {
System.out.println("Total Amount is positive");;

throw new Exception("Positive amount");

} 

Open in new window

0
 
mahjagAuthor Commented:
But if the value is less than zero - I got that error - I was confused since I did not handle the else part - I only wrote code to check the total amount value greater than zero - not sure why it did not work - I will test this again tomorrow - thanks for all your support For Yan..
0
 
for_yanCommented:
Add this printout  right befiore the parsing jsut in case, even though it repiosrt the contents of the string as part of exception, but te string should represent negative in this case, not 200,000.00
0
 
gordon_vt02Commented:
Also, what type of data does your database column represent?  If its currency or anything else that would require exact precision, you probably want to use java.math.BigDecimal instead and at least a double instead of a float.  You will probably still need to remove the commas from the String, but something like this should work and avoid rounding errors/loss of precision.

BigDecimal totalAmt = new BigDecimal(row.getTotalamt().replaceAll(",",""));
if (totalAmt.compareTo(BigDecimal.ZERO) > 0) {
    String message = "Total  Amount Cannot be Positive!";
    throw new OAException(message, OAException.ERROR);
}

Open in new window

0
 
mahjagAuthor Commented:
Hi Gordon Vt02

Appreciate your post - I applied your code and got this error

Error(592,35): variable ZERO not found in class java.math.BigDecimal

Any ideas?
0
 
for_yanCommented:
well, if you are doing it all for the real life bank transactions appliaction then BigDecimal is a way to go;
judging by how we interacted before, at this point you should not bother about it right now - there
are many things which you should overcome before being concrned with BigDeciimal
0
 
mahjagAuthor Commented:
Hi For Yan

Appreciate your feedback - reason why I was interested is the application has currency and has the amount that I specified before - want to see if BigDecimal will work - but again I have errors in compilation.
0
 
for_yanCommented:
My suggestion - try to make it work first with float - yesterdya you mentioned some strange
thing about not passing negative numbers - so klet's have it working in straightforward way -
then you'll deal with BigDecimal if you want and need
0
 
for_yanCommented:
Which vesrion of Java are you using?
I think BigDecimal.ZERO only appeared in 1.5
It qworks for me in 1.6

you can compare this way, I gues:


 if(bd.compareTo(new BigDecimal(0)) <0)System.out.println(true);

But I'd rather fisrt concentrate on havin it working in conventional way
0
 
mahjagAuthor Commented:
Yeah I tried it with both float and bigDecimal - I am gettig what I wanted if the results for Total Amt is greater than zero - I see the custom message that I had - but if the totalAmt is negative - which is a OK test case I am getting error after this code change - I get numberformat error - not sure why that is changing since I am not checking or changing the code that has total amount value less than zero - can't explain more why this happens - I even changed the spot to do this check to convert to float only when the totalAmt is greater than zero but still I see the error for my second test case when the total amount is negative - cannot attribute to why this happens -
0
 
mahjagAuthor Commented:
oracle.apps.fnd.framework.OAException: java.lang.NumberFormatException: (20052540) the negative value is 200525.40 - the value within brackets define it is negative -

0
 
for_yanCommented:
I see that is becuae your negative neumber is given as number withion parentheses
0
 
for_yanCommented:
I think you can do something with the locale and currency buut it is easier to do it this way:

float f = 1;
try{
String num = row.getTotalAmt();
boolean negative = false;
if(num.indexOf("(") > -1){
negative = true;
num = num.replaceAll("\\(","");
num = num.replaceAll("\\)","");

}
num = num.replaceAll(",","");

if(negative) num = "-"+num;
System.out.println("before parsing; " + num);

 f = Float.parseFloat(num);
} catch (Exception ex) {


System.out.println("Total Amount is not a number");;
throw new Exception("Total amount is not a numbe");
}

if(f > 0) {
System.out.println("Total Amount is positive");;

throw new Exception("Positive amount");

} 

Open in new window


let me check first if it wortks this way; I'll post soon
0
 
for_yanCommented:

yes this works fine:
        float fm = 1;
try{
String num = "(200,000.05)";
    num = num.trim();
boolean negative = false;
if(num.indexOf("(") > -1){
negative = true;
num = num.replaceAll("\\(","");
num = num.replaceAll("\\)","");

}
num = num.replaceAll(",","");

if(negative) num = "-"+num;
System.out.println("before parsing; " + num);

 fm = Float.parseFloat(num);
} catch (Exception ex) {


System.out.println("Total Amount is not a number");;
throw new Exception("Total amount is not a numbe");
}

if(fm > 0) {
System.out.println("Total Amount is positive");;


throw new Exception("Positive amount");

}

 System.out.println(fm);       

Open in new window


Output:
before parsing; -200000.05
-200000.05

Open in new window

0
 
for_yanCommented:

Do you mean that the number as it is coming to you does not contain decimal point:
(20052540) - ?

But the positive numbers, I thought, included the decimal point

If it does not have the decimal we'll need to modifty the code above, to make sure the numbers come corrrectly.
0
 
mahjagAuthor Commented:
Sorry for delays - my computer broke and I am rebuilding again - going to take atleast a day more to try the options
0
 
for_yanCommented:
take your time
0
 
mahjagAuthor Commented:
Thanks For Yan

I finally got my machine back and tried your segment of code and now I see it is working for both +ve and -ve Total Amount - I want to understand the code segments - can you explan - ? Again I am having problem with try and catch exception as I am getting "Error(582,1): unreported exception: java.lang.Exception; must be caught or declared to be thrown - I know you gave an expl for that but can you let me know from codewise what I need to do - Also can you explain each line in the code what it does - I know some of them are self explanatory but some others like  this -
  num = num.replaceAll("\\(","");
            num = num.replaceAll("\\)","");
needs to know why you do this 2 times - ? kind of if you can throw some light on your code then I understand better - especially the part when the total amount is negative first I thought I dont need to make any changes to the code - I only have to check if it is positive - but tourns out that the code errors if I dont format when the value is negative - I get format error when I dont add that code -
So I need some explanation - please - Thanks!!


//NEw code starts here ...
    float f = 1;
   
        String num = row1.getGrandTotal();
        boolean negative = false;
        if(num.indexOf("(") > -1){
            negative = true;
            num = num.replaceAll("\\(","");
            num = num.replaceAll("\\)","");
           }
        num = num.replaceAll(",","");
        if(negative) num = "-"+num;
        System.out.println("before parsing; " + num);
        f = Float.parseFloat(num);
 
  if(f >= 0) {
   System.out.println("Total Amount is positive");
   String message = "Total  Amount Cannot be Positive!";
    throw new OAException(message, OAException.ERROR);
   //throw new Exception("Positive amount");
}
// new code ends here
0
 
for_yanCommented:
If your negative code wouldf be coming like -200005.00 there would be no provlem but in database
it is stored as (2000005.00) - this is i don't know financial notation or waht buyt java does not
understand it (unlss nmaybe we do somthing spoecial)
so I had to remnove parentheses and also rememmeber is there were parentehses then we need to add the sign minus in front
 
 num = num.replaceAll("\\(",""); - removes left parenthese

   num = num.replaceAll("\\)",""); - removes right parenthese

replaceAll is a complex method (as opposed to reaplace ("","") whuich you do not have as you have  old java)
 it uses regular expressions - thatsat why you cant just   replace ("(","") in this way
because parenthese is a special charcatetr in reg Exp - so I neede to escaope it with two backslahse

If you want to read abourt reg exp read here:

http://www.regular-expressions.info/
and
http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

but it is a big topic - not so simple

If you are new to java and if you work alone  - don't throw exceptions - just check on the spot
if something wrong - then report to the users in error message
You want to throw exceptions if you are part of the team an you have requirements
to do that - beacsue other programmers will know that they will need to catcnthe the expections you are throwing





 
0
 
mahjagAuthor Commented:
the part that I dont understand is just becoz I touched the code that check for the value of totalAmt greater than zero I need to also touch the code where the totalAmt is negative - the ask was to check the total amount being greater than zero - the other part of being negative should have worked without touching the code - we are touching both values is my concern - needs more tesing now as oppose to only having test cases that have totalAmt positive.
0
 
CEHJCommented:
>>I see that is becuae your negative neumber is given as number withion parentheses

What makes you think it's anything to do with parentheses?

mahjag, please give examples of inputs you've found where the current code works and where it doesn't work
0
 
for_yanCommented:
It probably didn't work befire either - look at your aoriginal posting:

f (row.getTotalamt() > 0 ) - already this was wrong because your row.getTotalAmount() is a String and you acannopt compare it with number - that shoul have casued
compile errir rigth away and the code is interconnected - any time you change you have to thing what will happen when your data
have all possible values - it papens very often - you change thinking abiut one case and affect another case at the same moment
0
 
mahjagAuthor Commented:
Thanks CEHJ

Current code works for both TotalAmt being positive and negative value.

I have to add a code to check if it is positive then throw exception back to user saying it is error - since the appl only should allow a value of negative - that is all needed from code perspective -

but we are adding more code if the value is negative - that is why I am asking why? - I also see that from my testing I get an error if I dont handle negative value - if I take the entire code changes out - the appl works fine for both positive and negative value for total amount - that is why I am asking -

nothing specific I can give for input values - it is either positive or negative value that we can thnk of -
0
 
for_yanCommented:
You probably had differernt way of dealing with that before - if you post your original code
we may look at it - but it happens all the time - after any change - all cases should be tested.

Thios is what makes think that it will not work wth parentheses

        Float.parseFloat("(200)");

Open in new window


Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "(200)"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
	at java.lang.Float.parseFloat(Float.java:422)

	

Open in new window


This is pretty obvious.
0
 
CEHJCommented:
>>Exception in thread "main" java.lang.NumberFormatException: For input string: "(200)"

And where was that string please - with that value or any other?
0
 
for_yanCommented:

Look at this mahjag's comment ID:36532411

>oracle.apps.fnd.framework.OAException: java.lang.NumberFormatException: (20052540) the negative value is 200525.40 - the value within brackets define it is negative

I assume that it  should somehow work with currencyInstance and appropriate locale, but in simple way I could not achieve it,
so it was easier to strip away the parentheses and transform into minus

maybe they had original code which worked with it but I didn't see that code
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 25
  • 14
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now