[英]Hey so I cannot understand why iterating through this ArrayList is giving me a infinite loop?
Hey so I have just been using ArrayList for a particular problem but Here it is giving me an infinite loop still.嘿,所以我刚刚使用 ArrayList 来解决一个特定问题,但在这里它仍然给我一个无限循环。 According to logic the control should enter into one of the break statements after a few iterations but I just cannot figure out why I am getting this error.
根据逻辑,经过几次迭代后,控件应该进入其中一个中断语句,但我无法弄清楚为什么会出现此错误。 I have sorted the array b and I am comparing the contents of arraylist a with the maximum element of array b.
我已经对数组 b 进行了排序,并将 arraylist a 的内容与数组 b 的最大元素进行比较。 for eg- a= 1,2,3,4 and maximum of element b=3
例如- a= 1,2,3,4 和元素 b=3 的最大值
if the first element is lesser them max(b[]) then after removing that element the new arraylist becomes 2, 3,4 2 becomes the first element and so on and so forth.如果第一个元素小于它们 max(b[]) 则在删除该元素后,新的 arraylist 变为 2,3,4 2 变为第一个元素,依此类推。
package codechef; package 代码厨师;
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/*
5
3 1
4 3 5
6
3 3
2 4 7
2 3 7
3 3
2 7 4
2 7 3
4 4
2 6 5 1
4 6 5 2
2 2
7 4
7 4
*/
/* Name of the class has to be "Main" only if the class is public. */
class codechef2
{
public static void main (String[] args) throws java.lang.Exception
{
try
{
Scanner ob=new Scanner (System.in);
int t=ob.nextInt();
while(t-->0)
{
int n=ob.nextInt();
int m=ob.nextInt();
ArrayList <Integer> a=new ArrayList<Integer>();
int b[]=new int[m];
for(int i=0;i<n;i++)
{
a.add(ob.nextInt());
}
for(int i=0;i<n;i++)
{
System.out.println(a.get(i));
}
for(int i=0;i<m;i++)
{
b[i]=ob.nextInt();
}
ob.close();
Arrays.sort(b);
int j=0;
String str="";
boolean flag=false;
while(true)
{
if(b[m-1]>a.get(0))
{
a.remove(0);
}
if(a.get(0)>=b[m-1])
{
flag=true;
str="NO";
break;
}
if(a.isEmpty())
{
str="YES";
break;
}
}
System.out.println("brej");
if(flag)
{
System.out.println(str);
}
else
{
for(int i:b)
{
System.out.print(i+" ");
}
}
}
}
catch(Exception t)
{
return;
}
}
}
Look here:看这里:
while(true)
{
if(b[m-1]<a.get(0))
{
a.remove(0);
}
if(a.get(0)>=b[m-1])
{
flag=true;
str="NO";
break;
}
if(a.isEmpty())
{
str="YES";
break;
}
}
See something wrong with the logic?看到逻辑有问题吗?
b[m-1] < a.get(0)
is the exact same condition as a.get(0) >= b[m-1]
. b[m-1] < a.get(0)
与a.get(0) >= b[m-1]
的条件完全相同。 You need switch the logic to something like b[m-1]>=a.get(0)
to avoid an infinite loop, otherwise it won't break.您需要将逻辑切换到类似
b[m-1]>=a.get(0)
以避免无限循环,否则它不会中断。 I also suggest trying to use if / else if / else
for this kind of stuff.我还建议尝试使用
if / else if / else
来处理这类事情。
You can Fix your Programm with.您可以修复您的程序。
else { for(int i:b) { System.out.print(i+" "); else { for(int i:b) { System.out.print(i+" "); } break;
} 休息;
}
This will finish your doomsday Loop for while(True)这将完成你的世界末日循环 while(True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.