The Next Palindrome , Dont know why the Judge Is giving Wrong answer (code is in JAVA)

import java.util.;
import java.lang.
;

class Main
{
public static void main (String[] args) throws Exception
{

int rem; int no=0;
  int ar[]=new int[10];
  Scanner scan=new Scanner(System.in);
  int cases=0;
  if(scan.hasNextInt()) 
  {
	  cases = scan.nextInt();
  }
  
  for(int i=0 ; i<cases; i++)
  {    int z=0; 
	  if(scan.hasNextInt()) 
	  {
	     z = scan.nextInt();
	  }
	 
	  if(z<=1000000) ar[i]=z;
	
  }  
  
 for(int i= 0; i<cases ; i++)
	   
        {  if (ar[i]<=0) break;
	          int num=ar[i];
                 if(num<10)
                       {
                	     System.out.print((num+1)+" ");
                       }
                 else
                       {      
	            	    	  for(int m=num+1;m<=1111111; m++)
                	           {
                	    	     int ss=0; 
            		             int temp=m;
            		             int length=Integer.toString(temp).length();
		                         int[] arr=new int[length];
		                         while(temp>0)
		                              {    
		                	               {  rem=temp%10;
		                	                  arr[ss]=rem;
		                	                  temp=temp/10;
		                	                  ss++;
		                	               }
		                              }
		                          
		                         int flag=0;
		                           for(int g=0; g<length/2; g++)
		                        	  
		                              {if(arr[g]!=arr[length-(g+1)])
		                                {
		                        	        flag=4;
		                                }
		                        	   }
		                           if(flag==0)
		                           {
		                        	   System.out.print(m+" ");
		                        	   break;
		                           }
                             }
                       }    
                       }
 
}

}
//