如何摆脱Java中的无限循环?

迪皮蒂:
public class checkdivi {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
        if(sc.hasNext()){
            int T=sc.nextInt();
            int i=1;
            while(i <= T){
                int temp=T;

                    while((i%2) ==0 && (temp%2) ==0){
                            temp=temp/2;
                            i=i/2;
                            System.out.println("ok"+i);
                            if(i%2 !=0 || temp%2 !=0)
                                System.out.println("oh"+i);
                                break;                            
                        }               
                  System.out.println(""+i);
                  i=i+1;
                  System.out.println("yeah"+i);
            }                   
    }

}}

//当输入为12时,此代码将无限打印以下行。为什么i的值一次又一次变为1?

ok1
oh1
1
yeah2
普特南(Putnam):

您将设置i为,i/2而不是在嵌套的while循环中使用temp变量,因此每次它最终都会回退(i%2)==0 && (temp%2)==0由于您i最初将其设置为1,所以i即使仅在输入为偶数的情况下,也始终会在2时立即发生要解决此问题,请使用第二个临时变量存储i

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章