[英]java.lang.ArithmeticException: divide by zero
Having a lot of trouble with this. 有很多麻烦。 It runs on Android Nougat and Marshmallow but on Lollipop it won't work(mainly, my fireTV).
它可以在Android Nougat和Marshmallow上运行,但不能在Lollipop上运行(主要是我的fireTV)。 I'm getting the
java.lang.ArithmeticException: divide by zero
problem. 我得到
java.lang.ArithmeticException: divide by zero
问题。 Any ideas why is this crashing? 任何想法为什么会崩溃?
long startTime = System.currentTimeMillis();
InputStream is = response.body().byteStream();
BufferedInputStream bis = new BufferedInputStream(is);
long size = 0;
int red = 0;
byte[] buf = new byte[1024];
while ((red = bis.read(buf)) != -1) {
size += red;
}
long endTime = System.currentTimeMillis();
Log.d("ERROR CHECK", startTime + " " + endTime + " " + size);
double rate = (((size / 1024) / ((endTime - startTime) / 1000)) * 8); // THIS IS WHERE MY PROBLEM IS - A ZERO
// SOMEWHERE.
Log.d("ERROR CHECK", "No Zeros....");
rate = Math.round(rate * 100.0) / 100.0;
String ratevalue;
if (rate > 1000)
ratevalue = String.valueOf(rate / 1024).concat(" Mbps");
else
ratevalue = String.valueOf(rate).concat(" Kbps");
if (is != null) {
is.close();
}
if (bis != null) {
bis.close();
}
Log.d("download", "download speed = " + ratevalue);
The line where I indicated with the comment is where the problem is. 我在注释中指示的行就是问题所在。 All the values in that line are populated, I checked in that Log.d line before it.
该行中的所有值均已填充,我在该Log.d行中签入了它。
If the endTime - startTime
is less than 1000
, then the division operator will return 0
. 如果
endTime - startTime
小于1000
,则除法运算符将返回0
。 Divide by 1000.0
除以
1000.0
When denominator becomes zero because of small difference, it crashes. 当分母由于小差异而变为零时,它将崩溃。 Use doubles, check the denominator and if zero, make some value (like 1 or 0.1) as below.
使用双打,检查分母,如果为零,则如下所示生成一些值(例如1或0.1)。
double den = (endTime - startTime) / 1000.0)) * 8.0 ;
if(den==0) den= 0.1;
double rate = (((size / 1024) / (den);
I think code like this will fix your crash. 我认为像这样的代码将解决您的崩溃问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.