简体   繁体   中英

Value of Variable Keeps Resetting Every Time The Loop Runs (Java)

I'm currently working on a homework assignment for my Java OOP class. The assignment is that a mouse is trapped midway in a 30ft long pipe. The mouse needs to move randomly with a 50% chance of going left or right. The mouse can only move a random distance between a min of 3ft and a max distance of 8ft for each move made. The program should keep track of the distance that the mouse is from the left and right ends of the pipe after each move and once it has reached one end of the pipe, the loop should end and it should print out that the mouse has reached whatever end it reached. I'm using the variable fromendL to keep track of the mouse's distance from the left end and fromendR for the other end. The problem i'm encountering is that every time the loop runs it's resetting the values of each variable so and it's never giving me the distance over the course of multiple loops. Everything I believe I have working fine, although it might not be the most efficient way (i'm still fairly new to programming).

I'll attach the code below:

class Main {
  public static void main(String[] args)
  {
    int fromendL;
    int fromendR;
    int tMin = 3;
    int tMax = 8;
    int direction;
    int travel;
    int travelR = 15;
    int travelL = 15;
    boolean escaped = false;

    while (!escaped)
    {
      direction = (int)(Math.random()* 2 + 1);
      travel = (int)(Math.random() * (tMax - tMin) + 3);



      if (direction == 1)
      {
        fromendL = 15 - travel;
        fromendR = 30 - 15 + travel;
        travelL = travelL - travel;

        System.out.println("The mouse has moved: " + travel + " ft to the left" );
        System.out.println("The mouse is " + fromendL +" ft from The Left End");
        System.out.println("The mouse is " + fromendR +" ft from The Right End\n");

        if(travelL == 0 || travelL < 0)
        {
          escaped = true;
          System.out.println("The Mouse has escaped the Left end of the Pipe!");

        }

        else if (travelR == 30 || travelR > 30)
        {
          escaped = true;
          System.out.println("The Mouse has escaped the Right end of the Pipe!");
        }
      }

      else if (direction == 2)
      {
        fromendL = 15 + travel;
        fromendR = 30 - 15 - travel;
        travelR = travelR + travel; 
        System.out.println("The mouse has moved: " + travel + " ft to the right");
        System.out.println("The mouse is " + fromendL +" ft from The Left End");
        System.out.println("The mouse is " + fromendR +" ft from The Right End\n");

        if(travelR == 30 || travelR > 30)
          {
            escaped = true;
            System.out.println("The Mouse has escaped the Right end of the Pipe!");

          }

        else if (travelL == 0 || travelL < 0)
        {
          escaped = true;
          System.out.println("The Mouse has escaped the Left end of the Pipe!");
        }
      }




    }

  }
}

The following piece of code should solve the original problem. Please analyze it to find some of the improvements compared to your code.

Instead of using two variables to keep the position ( fromendL and fromendR ), I use a single one ( pos ). If I know the length of the pipe (which doesn't change) and the position starting from the left side of the pipe, the distance to the right end can be calculated.

Constructs like if (a == 0 || a < 0) are better written like if (a <= 0) in my opinion.

I use the direction as +1 or -1. Just like in mathematics, the negative direction is like going to the left, the positive direction is like going to the right.

The reason that your variables are reset every time lies in

    fromendL = 15 - travel;
    fromendR = 30 - 15 + travel;
    travelL = travelL - travel;

You start from 15 resp 30 over and over again instead of using the last position of the mouse.

My code looks like (I use tabs for indentation; my eyes are too old to see the subtle 2-character indentations ;) :

class Main {

    public static void main(String[] args)
    {
        static final int tMin = 3;
        static final int tMax = 8;
        static final int pLength = 30;
        int direction;
        int travel;
        int pos = pLength / 2;
        boolean escaped = false;

        while (!escaped) {
            direction = (int)(Math.random() * 2);
            if (direction == 0) direction = -1;
            travel = ((int)(Math.random() * (tMax - tMin)) + tMin) * direction;
            pos += travel;
            System.out.println("The mouse has moved: " + Math.abs(travel) + " ft to the " + (travel > 0 ? "right" : "left"));
            System.out.println("The mouse is " + pos +" ft from The Left End");
            System.out.println("The mouse is " + (pLength - pos) + " ft from The Right End\n");

            if (pos >= pLength || pos <= 0) {
                System.out.println("The Mouse has escaped the " +  (pos <= 0 ? "Left" : "Right") + " end of the Pipe!");
                escaped = true;
            }
        }
    }
}

The ? is a ternary operator. It tests the condition and if true, the expression evaluates to the value directly following the question mark. If false the expression evaluates to the value following the colon. Use it with care, many people don't like it and think it's confusing. And for that reason I've put it between parenthesis so it's clear where the construct starts and ends.

Since pos is either less or equal zero (escaped to the left) or greater or equal 30 (escaped to the right), I only have to test which of both it is. If I know the mouse didn't escape to the left it must have escaped to the right. (The condition of the if already guarantees that the mouse has escaped).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM