java - Use value outside for loop -


public class randomdemo {     public static void main(string[] args)     {         random rand = new random();         int [] vararray = new int[rand.nextint(10)];          system.out.println(vararray.length);         int d = rand.nextint(1999)-1000;         (int i=0;i<vararray.length;i++)         {             vararray[i]= rand.nextint(1999)-1000;             system.out.println(vararray[i]);              if(d==vararray[i])             {                 system.out.println(d);                       system.out.println(i+1);             }             else             {                  system.out.println(d);                 system.out.println(0);             }         }     } } 

problems in code:

it executes if-else statement multiple times , displays if-else output multiple times since in loop. code should execute if-else statement once rest of loop should executed multiple times. since if statement using value of vararray[i] cannot exclude code loop. when break statement used terminating for loop. , complete output not shown.

output: currently

7 -710 -249 0 -693 -249 0 172 -249 0 -488 -249 0 -48 -249 0 955 -249 0 869 -249 0

as can see length of array 7 displays array element value of variable d , value 0 in loop.

expected output:

7 -710 -693 172 -488 -48 955 869 -249 0

the output of array 7 elements should 7 array values followed variable d , 0.

may can set boolean flag track execution of if else code .. see code below.

    boolean flag = false;  // flag track if else      system.out.println(vararray.length);     int d = rand.nextint(1999)-1000;     (int i=0;i<vararray.length;i++)     {        ...        if(!flag){         if(d==vararray[i])         {             flag =true;             system.out.println(d);                   system.out.println(i+1);         }         else         {               flag =true;             system.out.println(d);             system.out.println(0);         }        } 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -