• JAVA progam issue for IF loop to and to chose what will get

    CatheriBurbank Member

    This is the task from Head First Java. It was all ok before i take to finish this task, i thought i will easy finish it. The task is to put for while loop offered possibilities and for if loop to and to chose what will get on the output.

    In this one i have to put while (x < 9) and if (index < 5) output is 14 and 1 . Somehow i thought output will be 20 and 1, when i check answer i saw i do not understand very well what is happening here. Can someone explain me how we get output 14 and 1 and what happen into the code?

    public class Mix4 {
    
       int counter = 0;
       
       public static void main(String[] args) {
    
          int count = 0;
          Mix4[] m4a = new Mix4[20];  // we are making 20 arrays
          int x = 0;
          
          while(x < 9) { // x is 0 and we will go through loop 0-8 times
             m4a[x] = new Mix4(); // we will make 8 array objects
             m4a[x].counter = m4a[x].counter + 1; // here i can't give reason what is happening
             count = count + 1; // count +1
             count = count + m4a[x].maybeNew(x); //
             x = x + 1;   // x + 1      
          }
          
          System.out.println(count + " " + m4a[1].counter); // why[1] ?
          
       }
       
       public int maybeNew(int index) {
          if (index < 5) {
             Mix4 m4 = new Mix4();
             m4.counter = m4.counter + 1;
             return 1; // why return 1?
          }
          
          return 0; // why return 0 ?
       }
    
    } 
    
  • SapnaVishwas Member

    The question isn’t designed to do anything productive, its purely to get you to keep track of what is happening inside the code. That is why it returns 1 or 0, and prints out a[1]. Programming questions are often like this to confuse you Smile

    maybeNew(..) never returns m4, so counter will only ever increase by 1 for each object in m4a.

    We’ll always increment the value of count by 2 if the index < 5. Otherwise we'll increase it by 1. So for x < 9; index < 5:

    0 to 4 will increase by 2 (5*2 = 10)
    5 to 8 will increase by 1 (4*1 = 4)
    

    So the final value of count is 14 and counter is 1

    x < 20; index < 5
    0 to 4 will increase by 2 (5 * 2 = 10)
    5 to 19 will increase by 1 (15 * 1 = 15)
    

    So the final value of count is 25 and counter is 1.

    x < 7; index < 7
    
    0 to 6 will increase by 2 (7 * 2 = 14)
    

    So the final value of count is 14 and counter is 1.

    x < 19; index < 1
    
    0 will increase by 2 (1 * 2 = 2)
    1 to 18 will increase by 1 (18 * 1 = 18)
    

    So the final value of count is 20 and counter is 1.

  • BuckRenard Member

    you can see i didn’t continue to learn this for a 4 days Sad, i was disappointed and didn’t have a lot of time, without free few hours it is nothing for a learning. Now i am trying to understand but still i am not sure what is happening here. What i miss when i can’t figure it out? Many basic thing in programming (theory) is not so hard to learn it is much more harder to understand when you have a lot of pieces into a task. Look here, look there, that is for that and that, call that here, than create that,.. Sad

    Let’s try with while (x < 2) where we get for output 4 and 1

    a first true statment 0 < 2
    we create a first array object
    m4a[0] = new mix4();
    
    instance variable counter of class Mix4
    counter is now 1
    
    count is now 1
    
    this line
    count = count + m4a[x].maybeNew(x);
    count = 1 + m4a[0].maybeNew(0);
    
    give us for now 2? 2 = 1 + 0 right? We created first object m4a[x] which in first loop 0 and access to method maybeNew is (0) too which when we increment it will give us +1 to to the count .
    
    x is now 1
    --------------------
    the last true while statement 1 < 2
    we have now a new object of array
    m4a[1] = new mix();
    
    counter is now 2
    count is now 3 if up is all ok
    
    count = count + m4a[1].maybeNew(1);
    
    result 4 = 3 + 1
    
    after 5 times in loop of method maybeNew it wont any more increment x for 2 and here count = count + m4a[x].maybeNew(x); we wont do nothing it will be useless line, count will only increment this line count = count + 1; Am i right? Or return 1; is there to tell put into x number 1 ?
    
    These lines
    Mix4 m4 = new Mix4();
    m4.counter = m4.counter + 1;
    aren't doing nothing and there are only for confusing, how you said. When i comment them i get all the same.
    
    I am still confused for return 0; except we must have return value because it is method which is returning something. Is return 0; here when if loop is finished then we will put here count = count + m4a[x].maybeNew(0); for maybeNew(0) right?
    

    It is ok for now because i do not understand this very well? Can we call this smallpox for programming Smile? Sometimes i doubt will i ever learn and become good in programming.
    I am learning for a several months but i have pauses sometimes for a week, sometimes for a month. Now i start almost all from beginning to learn.

  • Abhey Member

    Don’t worry man, programming is a bit of a mindfug at times. You’ll get your head around it. Just take a break when you need to and use a pen and paper to write down the state of each variable.

    I think you’re just getting a bit confused with all the variables and because the variable and method names are not sensible?

    I simplified the program by removing unnecessary code and renaming some of the variables to something more sensible (for me at least). I didn’t comment on all the code as you already seem to understand most of it.

    Get out a piece of paper or use Excel to write down all the variables and for each increment of x, write down the new value of each variable in a new row.

    public class Mix4 {
    
        int visits = 0;
    
        public static void main(String[] args) {
            int count = 0;
            Mix4[] m4a = new Mix4[20];
            int position = 0;
    
            while (position < 2) {
                m4a[position] = new Mix4();
    
                // Counter only gets incremented once so this is equivalent to m4a[x].counter = m4a[x].counter + 1;
                m4a[position].visits = 1;
                count = count + 1;
    
                // This line checks if the while loop has executed less times than the limit (limit = 2 in this example)
                // After it is done checking if position is < 2, it adds the result to the counter
                // So in our example, this will be:
                // count = 1 + 1 when position = 0 (because 0 < 2)
                // count = 1 + 1 when position = 1 (because 1 < 2)
                count = count + m4a[position].checkIfLimitIsGreaterThan(position);
                position = position + 1;
            }
    
            // Answer will be 4 1
            System.out.println(count + " " + m4a[1].visits);
        }
    
        public int checkIfLimitIsGreaterThan(int currentPosition) {
    
            // currentPosition can be 0 or 1
            // limit is 2
            if (currentPosition < 2) {
                return 1;
            } else {
                return 0;
            }
        }
    }
    

    As for the second example, maybe try to think about what each statement in the snippet pool needs before it can be used.

  • ShikhaTan Member

    This is look much more clearer and understandable. Probably i did not get used to to coding and to analysis code with “classic” and short names for variables. I like how you explained to me. Examples in this way would be much more easier for beginners. Thank you very much i really appreciate it.

  • SapnaVishwas Member

    I added some printf statements (similar to println) that will hopefully clear up the flow of the program for you.

    public class Puzzle4 {
    
        public static void main(String[] args) {
            Puzzle4b[] obs = new Puzzle4b[6];
    
            int y = 1;
            int x = 0;
            int result = 0;
            while (x < 6) {
                obs[x] = new Puzzle4b();
                obs[x].ivar = y;
                System.out.printf("Setting obs[x] to [%s]\n", y);
    
                y = y * 10;
                x = x + 1;
            }
    
            x = 6;
            while (x > 0) {
                x = x - 1;
                result = result + obs[x].doStuff(x);
                System.out.printf("Interim result for x [%s] is [%s]\n", x, result);
            }
            System.out.println("result " + result);
        }
    }
    
    class Puzzle4b {
    
        int ivar;
        public int doStuff(int factor) {
            if (ivar > 100) {
                System.out.printf("[%s] > 100, so return ivar * factor [%s]\n", ivar, ivar * factor);
                return ivar * factor;
            } else {
                System.out.printf("[%s] <= 100, so return ivar * (5 - factor) [%s]\n", ivar, ivar * (5 - factor));
                return ivar * (5 - factor);
            }
        }
    }
Viewing 5 reply threads
  • You must be logged in to reply to this topic.
en_USEnglish