[英]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.