为Android优化Java代码基础,价格为0.99美分(含税)



这个想法是使用一个函数来查找包含税的正确价格,以便价格以0.99结尾,例如,如果成本是1.33美元,则最终价格应该以1.99美元结尾,包括税。因此,所示的代码在本机java中工作得非常好,但要在Android中实现,即使我使用RxJava在Android的后台线程上运行,java也会出现内存错误。

这是我在android中使用的Java代码:

public class Main {
static  int counts = 0;
public static void main(String[] args) {
// write your code here
System.out.println("Price to use : " + findPriceToCharge99(Double.parseDouble("0.05" ) , .15 ) + "  :::counts "+counts);
}
public static double roundDecimalPlaces(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
static double findPriceToCharge99(double price,double taxVal){
price= roundDecimalPlaces(price ,2);
double taxAmount = (price)  * taxVal ;
counts++;
String check = roundDecimalPlaces((price + taxAmount),2)+"";
return  check.split("\.")[1].equals("99") ? price : findPriceToCharge99(price+.01 ,taxVal);
}
}

这是我的堆栈跟踪:


2021-03-12 08:27:40.288 18794-19179/com.app E/AndroidRuntime: FATAL EXCEPTION: RxCachedThreadScheduler-2
Process: com.app, PID: 18794
io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | java.lang.StackOverflowError: stack size 1039KB
at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:367)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:69)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.StackOverflowError: stack size 1039KB
at java.lang.ref.PhantomReference.<init>(PhantomReference.java:80)
at sun.misc.Cleaner.<init>(Cleaner.java:115)
at sun.misc.Cleaner.create(Cleaner.java:133)
at libcore.util.NativeAllocationRegistry.registerNativeAllocation(NativeAllocationRegistry.java:242)
at java.math.BigInt.makeValid(BigInt.java:48)
at java.math.BigInt.putULongInt(BigInt.java:83)
at java.math.BigInteger.<init>(BigInteger.java:105)
at java.math.BigInteger.valueOf(BigInteger.java:375)
at java.math.BigDecimal.getUnscaledValue(BigDecimal.java:2946)
at java.math.BigDecimal.doubleValue(BigDecimal.java:2552)

为未来的研究人员

int price = 99 ;
float x = Float.valueOf(price) / 100 ;
Result : 0.99

最新更新