waltermilner

Untitled

Sep 17th, 2017
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1. public class Test {
  2.  
  3.    int counter = 0;
  4.     public static void main(String[] args) {
  5.         int count = 0;
  6.         Test [] m4a = new Test[20]; // make an array
  7.         int x = 0;
  8.         while (x < 20) { // loop x is 0 to 19
  9.           // so we do this 20 times
  10.             m4a[x] = new Test(); // make an instance an dput in array
  11.             m4a[x].counter = m4a[x].counter +1; // the counter field
  12.             // of this instance is now 1
  13.            
  14.             count = count +1 ; // increment count by 1 (adds a total of 20)
  15.             count = count + m4a[x].maybeNew(x); // and maybe
  16.             // maybe is 1 for x 0 to 4 - so add in a total of 5
  17.            
  18.             x=x+1;
  19.            
  20.            
  21.          
  22.         }
  23.         System.out.println(count + "" + "\t" + m4a[1].counter);
  24.         // outputs 25 1
  25.        
  26.     }
  27.         public int maybeNew(int index){
  28.             if(index<5){ // so if x is 0 to 4 - that is, 5 times
  29.                 Test m4 = new Test(); // this is pointless
  30.                 // m4 is a local variable, created on teh stack, and
  31.                 // disappears at the endo f this method
  32.                 m4.counter = m4.counter + 1;
  33.                 return 1; // so we return 1 if index is 0 to 4
  34.             }
  35.             return 0; // otherwise return 0
  36.         }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment