繁体   English   中英

在 java 中摆脱这个无限循环的方法是什么?

[英]what is the way to get out of this infinite loop in 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

您将i设置为i/2而不是在嵌套的 while 循环中使用临时变量,因此每次(i%2)==0 && (temp%2)==0时它最终都会返回; 因为您最初将i设置为 1,所以只要i为 2,这总是会发生,尽管只有当输入是偶数时才会发生。 要解决此问题,请使用第二个临时变量来存储i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM