什么语句造成java程序崩溃,是什么导致Java(冰雹序列)在我的程序中崩溃

I´ve made a program that does the (usually called) hailstone sequence, The program basically does this:

creates an int (value) and assign it a value.

If the int is even, divide it by two.

If the int is odd, multiply it by three and add one. Continue this process until n is equal to one.

it seems to be working fine with most numbers, but this number 99888769, the app hangs on a negative integer. Why is this?, they say that no-one has yet been able to proove that it stops, I´m not expecting I have solved that. But would be interesting to know why my app stops. -

private void hailStoneSequence(){

int value = 99888769;

int i = 0;

boolean trueOrFalse = isOddOrEven (value);

while (value != 1){

while (trueOrFalse == true && value != 1){

i++;

int previousValue = value;

value = value / 2;

println( previousValue +" is even, so I take half: "+value);

trueOrFalse = isOddOrEven (value); // returning true or false, and inserting the newly divided number. So that it breaks loop when nescesary.

}

while (trueOrFalse == false && value != 1){

i++;

int previousValue = value;

value = (value * 3) + 1;

println (previousValue +" is odd, so I make 3n+1: "+value);

trueOrFalse = isOddOrEven (value);

}

}

println ("\n\nThe process took "+i+" to reach "+value);

}

private boolean isOddOrEven(int value){

/*

* Takes an value and returns true, if that number is even.

* Else it returns false.

*/

if (value % 2 != 0){

return false;

}else{

return true;

}

}

}

解决方案

As you keep increasing ints, they will eventually (in what might seem like a startling behavior) become negative because you are surpassing the maximum value of the int type (2^31-1), i.e. you end up changing the bit (of the int's binary representation) that is used to store the sign of the number. Use long instead.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值