循环停止运行java

循环停止运行java,java,Java,对于下面的代码,当“n”约为100000时,它将停止运行。我需要它一直运行到一百万。我不知道哪里出错了,我还在学习Java,所以代码中可能也有简单的错误 public class Problem14{ public static void main(String[] args) { int chainLength; int longestChain = 0; int startingNumber = 0; for(int n =2; n<=1000000;

对于下面的代码,当“n”约为100000时,它将停止运行。我需要它一直运行到一百万。我不知道哪里出错了,我还在学习Java,所以代码中可能也有简单的错误

 public class Problem14{
public static void main(String[] args) {
    int chainLength;
    int longestChain = 0;
    int startingNumber = 0;
    for(int n =2; n<=1000000; n++)
    {
        chainLength = getChain(n);
        if(chainLength > longestChain)
        {
            System.out.println("chainLength: "+chainLength+" start: "+n);
            longestChain = chainLength;
            startingNumber = n;
        }
    }

    System.out.println("longest:"+longestChain +" "+"start:"+startingNumber);
}
public static int getChain(int y)
{
    int count = 0;
    while(y != 1)
    {
        if((y%2) == 0)
        {
            y = y/2;
        }
        else{
            y = (3*y) + 1;
        }
        count = count + 1;
    }

    return count;   
}
}
公共类问题14{
公共静态void main(字符串[]args){
整数链长;
int longestChain=0;
int startingNumber=0;
对于(int n=2;n最长链)
{
System.out.println(“链长:+chainLength+”开始:+n);
最长链=链长;
起始数=n;
}
}
System.out.println(“最长:+longestChain+”+“开始:+startingNumber”);
}
公共静态int-getChain(int-y)
{
整数计数=0;
而(y!=1)
{
如果((y%2)==0)
{
y=y/2;
}
否则{
y=(3*y)+1;
}
计数=计数+1;
}
返回计数;
}
}

请使用
long
作为
数据类型
而不是
int


我想让这件事曝光,这个数字确实超过了1000000,所以变量
y
需要
long
来保存它。

它是y的数据类型。它应该是长的。否则将达到-20亿


我想我意识到了这一点——这是欧拉问题14。我自己也这么做过。

getChain()方法导致了问题,它变为负值,然后永远挂起在循环中。

我只是好奇-代码的目的通常是什么?您是否尝试捕获异常以查看是否抛出了未经处理的异常?可能是堆栈溢出?我正在做Euler项目,它是一个你必须解决数学问题的网站。这里是我正在做的问题:您的程序是崩溃还是停止生成输出?您确定它停止执行吗?如果
chainLength>longestChain
不正确,则不会打印任何内容。也许你只是在等待的时间里没有找到更长的链条?在else的情况下,试着为该条件打印一些东西(比如
n
),100万在32位整数范围内-仍在试图找出错误!对于
n
?1000000在
int
范围内很合适。实际上他是对的,当应用get-Chain方法时,数字确实会大于1000000。我只是没意识到。从int改为int后工作正常long@KumarVivekMitra:编辑您的帖子,以便我可以更改我的投票。干得好@KumarVivekMitra如果你解释了原因,也许人们不会这么快给你负面的观点,但正如我说的,你已经做到了:)。是的,谢谢,Kumar击败了你:),所以我会把他的答案标记为正确。你不需要这个函数,只要把while放在for中就行了。在执行链之前,将n复制到一个长变量中。您可以清理的其他内容是使用诸如y/=2而不是y=y/2和count++而不是count=count+1等操作符。