Search code examples
javawhile-loopnested-loopsinfinite-loop

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);
            }                   
    }

}}

//This code is printing the below lines infinitely when the input is given as 12. Why is the value of i becoming 1 again and again ?

ok1
oh1
1
yeah2

Solution

  • You're setting i to i/2 instead of using a temp variable in the nested while loop, so it ends up going back down every time (i%2)==0 && (temp%2)==0; since you set i to 1 initially, this will always happen as soon as i is 2, though only when the input is even. To fix this, use a second temporary variable to store i.