Moving in a box

By Dr. Nicholas Duchon

The code:


// File: BoxND.java
// Date: Apr 30, 2016
// Author: Nicholas Duchon
// Purpose: step a line around a box
//    showing reflections

import java.util.Scanner;

public class BoxND {
   double x, y, vx, vy, bx, by;
   Scanner sn = new Scanner (System.in);
  
   public BoxND () {
      System.out.print ("Enter box size, initial x, y and vx and vy: ");
      bx = sn.nextDouble ();
      by = sn.nextDouble ();
       x = sn.nextDouble ();
       y = sn.nextDouble ();
      vx = sn.nextDouble ();
      vy = sn.nextDouble ();
      sn.nextLine(); // eat end of line from this input
      while (menu());
      System.out.println (".. Bye");
   } // end no parameter constructor
  
   public boolean menu () {
      System.out.print ("enter timeand step  as doubles or q to quit: ");
      String line = sn.nextLine();
      if (line.trim().startsWith ("q")) return false;
      double t = 0, step = 1.0;
      Scanner st = new Scanner (line);
      try {
         t = st.nextDouble ();
         step = st.nextDouble ();
      }
      catch (NumberFormatException e) {return true;}
      for (double tn = 0; tn < t; tn+= step)
         System.out.printf ("%.1f %.1f %.1f\n", tn, getX (tn), getY (tn));
//       System.out.printf ("f(%5.1f) = (%4.1f, %4.1f)\n", tn, getX (tn), getY (tn));
      return true;
  
} // end method menu
  
   public double getX (double t) {
      double xt = 65.54;
      double xn0 = x / bx;
      double vnx = vx / bx;
      double xnt = xn0 + vnx * t;
      xnt = xnt % 2;
      if (xnt < 0) xnt += 2;
      if (xnt > 1) xnt = 2 - xnt;
      return xnt * bx;
  
} //end method getX
  
   public double getY (double t) {
      double yt = 65.54;
      double yn0 = y / by;
      double vny = vy / by;
      double ynt = yn0 + vny * t;
      ynt = ynt % 2;
      if (ynt < 0) ynt += 2;
      if (ynt > 1) ynt = 2 - ynt;
      return ynt * by;
  
} // end method getY
  
   public static void main (String args []) {
      BoxND b = new BoxND ();
  
} //end main
} // end class BoxND


Date: Apr 30, 2016