Código de cuenta regresiva: 'League of Legends' -- java campo con game campo con timer camp codereview Relacionados El problema

Countdown Code: 'League of Legends'


26
vote

problema

Español

He escrito algún código para rastrear los buffs como una adición lateral al juego popular League of Legends .

Mi código es increíblemente repetitivo y también tengo la cuestión de no poder rastrear múltiples a los buffs, aunque eso podría no estar sobre el tema para la pregunta, así que siéntase libre de no considerar esto al responder.

  import java.util.Scanner;   public class MainProgram {      public static void main(String[] args) {          Scanner keyboard = new Scanner(System.in);              System.out.println("Jungle Timers v1.0");          System.out.println(" Select a buff to time:");         System.out.println(" 1. Blue");         System.out.println("2. Enemy Blue");         System.out.println("3. Red");         System.out.println("4. Enemy Red");         System.out.println("5. Dragon");         System.out.println("6. Baron");          System.out.print(" >  ");         int timerChoice = keyboard.nextInt();          keyboard.close();          switch (timerChoice) {         case 1:             friendlyBlue();         case 2:             enemyBlue();         case 3:             friendlyRed();         case 4:             enemyRed();         case 5:             Dragon();         case 6:             Baron();             }      }      public static void friendlyBlue() {         System.out.println(" Tracking your blue...");         System.out.println("5 Minutes left");         int friendlyBlue = 300;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + friendlyBlue;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Blue Buff is up!");                 }             }         }     }      public static void enemyBlue() {         System.out.println(" Tracking enemy blue...");         System.out.println("5 Minutes left");         int enemyBlue = 300;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + enemyBlue;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Enemy Blue Buff is up!");                 }             }         }     }      public static void friendlyRed() {         System.out.println(" Tracking your red...");         System.out.println("5 Minutes left");         int friendlyRed = 300;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + friendlyRed;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Red Buff is up!");                 }             }         }     }      public static void enemyRed() {         System.out.println(" Tracking enemy red...");         System.out.println("5 Minutes left");         int enemyRed = 300;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + enemyRed;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Enemy Red Buff is up!");                 }             }         }     }      public static void Dragon() {         System.out.println(" Tracking dragon...");         System.out.println("6 Minutes left");         int dragon = 360;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + dragon;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 300)                         System.out.println("5 Minutes left");                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Dragon is up!");                 }             }         }     }      public static void Baron() {         System.out.println(" Tracking baron...");         System.out.println("7 Minutes left");         int baron = 420;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + baron;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 360)                         System.out.println("6 Minutes left");                     if (endTime - startTime == 300)                         System.out.println("5 Minutes left");                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Baron is up!");                 }             }         }     } }   
Original en ingles

I have written some code to track buffs as a side addition to the popular game League of Legends.

My code is incredibly repetitive and I also have the issue of not being able to track multiple buffs, although that might not be on topic for the question so feel free to not consider this when answering.

import java.util.Scanner;   public class MainProgram {      public static void main(String[] args) {          Scanner keyboard = new Scanner(System.in);              System.out.println("Jungle Timers v1.0");          System.out.println("\nSelect a buff to time:");         System.out.println("\n1. Blue");         System.out.println("2. Enemy Blue");         System.out.println("3. Red");         System.out.println("4. Enemy Red");         System.out.println("5. Dragon");         System.out.println("6. Baron");          System.out.print("\n>  ");         int timerChoice = keyboard.nextInt();          keyboard.close();          switch (timerChoice) {         case 1:             friendlyBlue();         case 2:             enemyBlue();         case 3:             friendlyRed();         case 4:             enemyRed();         case 5:             Dragon();         case 6:             Baron();             }      }      public static void friendlyBlue() {         System.out.println("\nTracking your blue...");         System.out.println("5 Minutes left");         int friendlyBlue = 300;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + friendlyBlue;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Blue Buff is up!");                 }             }         }     }      public static void enemyBlue() {         System.out.println("\nTracking enemy blue...");         System.out.println("5 Minutes left");         int enemyBlue = 300;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + enemyBlue;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Enemy Blue Buff is up!");                 }             }         }     }      public static void friendlyRed() {         System.out.println("\nTracking your red...");         System.out.println("5 Minutes left");         int friendlyRed = 300;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + friendlyRed;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Red Buff is up!");                 }             }         }     }      public static void enemyRed() {         System.out.println("\nTracking enemy red...");         System.out.println("5 Minutes left");         int enemyRed = 300;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + enemyRed;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Enemy Red Buff is up!");                 }             }         }     }      public static void Dragon() {         System.out.println("\nTracking dragon...");         System.out.println("6 Minutes left");         int dragon = 360;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + dragon;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 300)                         System.out.println("5 Minutes left");                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Dragon is up!");                 }             }         }     }      public static void Baron() {         System.out.println("\nTracking baron...");         System.out.println("7 Minutes left");         int baron = 420;         long startTime = System.currentTimeMillis() / 1000;         long endTime = startTime + baron;          while (System.currentTimeMillis() / 1000 < endTime) {             while (startTime != System.currentTimeMillis() / 1000) {                 startTime += 1;                 if (endTime - startTime > 1)                     if (endTime - startTime == 360)                         System.out.println("6 Minutes left");                     if (endTime - startTime == 300)                         System.out.println("5 Minutes left");                     if (endTime - startTime == 240)                         System.out.println("4 Minutes left");                     if (endTime - startTime == 180)                         System.out.println("3 Minutes left");                     if (endTime - startTime == 120)                         System.out.println("2 Minutes left");                     if (endTime - startTime == 60)                         System.out.println("1 Minute left");                     if (endTime - startTime == 30)                         System.out.println("30 Seconds left");                     if (endTime - startTime == 15)                         System.out.println("15 Seconds left");                     if (endTime - startTime == 5)                         System.out.println("5 Seconds left");                 else if (endTime - startTime == 1) {                     System.out.println("Baron is up!");                 }             }         }     } } 
        
     
     

Lista de respuestas

21
 
vote
vote
La mejor respuesta
 

(revisión relativamente crítica ... Disculpas por adelantado)

Los dos problemas que siento son más incorrectos acerca de su código es la declaración del interruptor de buggy, y la mala elección del mecanismo de sincronización. La decisión de utilizar estos mecanismos ha llevado a un diseño de OOP pobre.

Interruptor

primero, sin embargo, el error del interruptor:

  switch (timerChoice) { case 1:     friendlyBlue(); case 2:     enemyBlue(); case 3:     friendlyRed(); case 4:     enemyRed(); case 5:     Dragon(); case 6:     Baron();     }   

Si el usuario elige 1, lo harán todo !!! Sus casos de conmutación deben 'romper':

  switch (timerChoice) { case 1:     friendlyBlue();     break; case 2:     enemyBlue();     break; case 3:     friendlyRed();     break; case 4:     enemyRed();     break; case 5:     Dragon();     break; case 6:     Baron();     break;     }   

Otros problemas relacionados con el código-convenciones (como la de la mayúscula B en Baron , y D IN Dragon no son tan significativos).

Las declaraciones de casos en Java son 'caídas', y debe romperse a menos que desee que las siguientes afirmaciones se ejecuten también.

TIMER

En Java, la solución adecuada para cualquier problema de tiempo, es usar las funciones del temporizador de la biblioteca. En las versiones recientes de Java, la herramienta adecuada es la ScheduledExecutorService . Este servicio le permite programar tareas en el futuro.

Yo lo construiría algo así:

  private final class TimedEvent {     private final long preTarget;     private final String message;     TimedEvent(long millis, String message) {         this.preTarget = millis;         this.message = message;     }     private long delayTo(final long target) {         return target - preTarget;     } }  .....  public static final TimedEvent[] EVENTS = {     new TimedEvent(240000, "4 Minutes left"),     new TimedEvent(180000, "3 Minutes left"),     new TimedEvent(120000, "2 Minutes left"),     new TimedEvent(60000,  "1 Minute left"),     new TimedEvent(30000,  "30 Seconds left"),     new TimedEvent(15000,  "15 Seconds left"),     new TimedEvent(5000,   "5 Seconds left"),     new TimedEvent(1000,   "1 Second left") };  ....   

Luego, con la configuración de TimedEvents, puede programarlos en un bucle, contando hacia la hora de destino .....

  final long now = System.currentTimeMillis(); final long target = now + sometime; /// whatever you are counting down to.... for (final TimedEvent te : EVENTS) {     long delay = te.delayTo(target);     if (delay >= 0) {         Callable<Object> torun = new Callable<Void>() {             public void call() {                 System.out.println(te.getMessage());                 return null;             }         }         scheduler.schedule(torun, delay, TimeUnit.MILLISECONDS);     } }   
 

(relatively critical review ... apologies in advance)

The two issues I feel are most incorrect about your code is the buggy switch statement, and the poor choice of timing mechanism. The decision to use these mechanisms has lead to a poor OOP design.

Switch

First, though, the switch bug:

switch (timerChoice) { case 1:     friendlyBlue(); case 2:     enemyBlue(); case 3:     friendlyRed(); case 4:     enemyRed(); case 5:     Dragon(); case 6:     Baron();     } 

If the user chooses 1, they will do everything!!! Your switch cases should 'break':

switch (timerChoice) { case 1:     friendlyBlue();     break; case 2:     enemyBlue();     break; case 3:     friendlyRed();     break; case 4:     enemyRed();     break; case 5:     Dragon();     break; case 6:     Baron();     break;     } 

Other problems related to code-conventions (like the upper-case B in Baron, and D in Dragon are not as significant).

Case statements in Java are 'fall-through', and you need to break unless you want the following statements to execute as well.

Timer

In Java, the right solution for any timing problem, is to use the library timer functions. In recent Java versions, the right tool is the ScheduledExecutorService. This service allows you to schedule tasks in the future.

I would build it something like:

private final class TimedEvent {     private final long preTarget;     private final String message;     TimedEvent(long millis, String message) {         this.preTarget = millis;         this.message = message;     }     private long delayTo(final long target) {         return target - preTarget;     } }  .....  public static final TimedEvent[] EVENTS = {     new TimedEvent(240000, "4 Minutes left"),     new TimedEvent(180000, "3 Minutes left"),     new TimedEvent(120000, "2 Minutes left"),     new TimedEvent(60000,  "1 Minute left"),     new TimedEvent(30000,  "30 Seconds left"),     new TimedEvent(15000,  "15 Seconds left"),     new TimedEvent(5000,   "5 Seconds left"),     new TimedEvent(1000,   "1 Second left") };  .... 

Then, with the TimedEvents set up, you can schedule them in a loop, counting down to the target time.....

final long now = System.currentTimeMillis(); final long target = now + sometime; /// whatever you are counting down to.... for (final TimedEvent te : EVENTS) {     long delay = te.delayTo(target);     if (delay >= 0) {         Callable<Object> torun = new Callable<Void>() {             public void call() {                 System.out.println(te.getMessage());                 return null;             }         }         scheduler.schedule(torun, delay, TimeUnit.MILLISECONDS);     } } 
 
 
12
 
vote

Podría sacar el bucle 9988776665544337 de cada función y hacerlo su propia función. Algo así como este

  private static void Countdown(long startTime, long endTime, string finalMsg){     while (System.currentTimeMillis() / 1000 < endTime) {         while (startTime != System.currentTimeMillis() / 1000) {             startTime += 1;             if (endTime - startTime > 1) {                 if (endTime - startTime == 240)                     System.out.println("4 Minutes left");                 if (endTime - startTime == 180)                     System.out.println("3 Minutes left");                 if (endTime - startTime == 120)                     System.out.println("2 Minutes left");                 if (endTime - startTime == 60)                     System.out.println("1 Minute left");                 if (endTime - startTime == 30)                     System.out.println("30 Seconds left");                 if (endTime - startTime == 15)                     System.out.println("15 Seconds left");                 if (endTime - startTime == 5)                     System.out.println("5 Seconds left");             } else if (endTime - startTime == 1) {                 System.out.println(finalMsg);             }         } }   

Luego de cada función, llame a la función de cuenta regresiva. Creo que se verá un poco más limpio y menos repetitivo.

 

You could pull out the while loop of each function and make it its own function. Something like this

private static void Countdown(long startTime, long endTime, string finalMsg){     while (System.currentTimeMillis() / 1000 < endTime) {         while (startTime != System.currentTimeMillis() / 1000) {             startTime += 1;             if (endTime - startTime > 1) {                 if (endTime - startTime == 240)                     System.out.println("4 Minutes left");                 if (endTime - startTime == 180)                     System.out.println("3 Minutes left");                 if (endTime - startTime == 120)                     System.out.println("2 Minutes left");                 if (endTime - startTime == 60)                     System.out.println("1 Minute left");                 if (endTime - startTime == 30)                     System.out.println("30 Seconds left");                 if (endTime - startTime == 15)                     System.out.println("15 Seconds left");                 if (endTime - startTime == 5)                     System.out.println("5 Seconds left");             } else if (endTime - startTime == 1) {                 System.out.println(finalMsg);             }         } } 

Then from each function, call the Countdown function. I think it will look a little cleaner and less repetitive.

 
 
     
     
11
 
vote

Primero: creo que el punto @dford hace es bastante bueno.

segundo, creo que deberías trabajar mejor en su código. En particular, la sangría de su principal if / switch (timerChoice) { case 1: friendlyBlue(); break; case 2: enemyBlue(); break; case 3: friendlyRed(); break; case 4: enemyRed(); break; case 5: Dragon(); break; case 6: Baron(); break; } 0 / switch (timerChoice) { case 1: friendlyBlue(); break; case 2: enemyBlue(); break; case 3: friendlyRed(); break; case 4: enemyRed(); break; case 5: Dragon(); break; case 6: Baron(); break; } 1 la cadena es engañosa:

  switch (timerChoice) { case 1:     friendlyBlue();     break; case 2:     enemyBlue();     break; case 3:     friendlyRed();     break; case 4:     enemyRed();     break; case 5:     Dragon();     break; case 6:     Baron();     break;     } 2  

Cuando un switch (timerChoice) { case 1: friendlyBlue(); break; case 2: enemyBlue(); break; case 3: friendlyRed(); break; case 4: enemyRed(); break; case 5: Dragon(); break; case 6: Baron(); break; } 3 Sigue a una cadena de sentencias switch (timerChoice) { case 1: friendlyBlue(); break; case 2: enemyBlue(); break; case 3: friendlyRed(); break; case 4: enemyRed(); break; case 5: Dragon(); break; case 6: Baron(); break; } 4 , se conecta al 99887766555443315 que ya no tiene un demás. Una declaración switch (timerChoice) { case 1: friendlyBlue(); break; case 2: enemyBlue(); break; case 3: friendlyRed(); break; case 4: enemyRed(); break; case 5: Dragon(); break; case 6: Baron(); break; } 6655443316 Controla exactamente una declaración siguiente (que necesita ser una declaración compuesta si desea que controle más de una declaración sintáctica). En otras palabras, el código realmente funciona como:

  switch (timerChoice) { case 1:     friendlyBlue();     break; case 2:     enemyBlue();     break; case 3:     friendlyRed();     break; case 4:     enemyRed();     break; case 5:     Dragon();     break; case 6:     Baron();     break;     } 7  

Basado en su sangría, al parecer, quería que fuera más así:

  switch (timerChoice) { case 1:     friendlyBlue();     break; case 2:     enemyBlue();     break; case 3:     friendlyRed();     break; case 4:     enemyRed();     break; case 5:     Dragon();     break; case 6:     Baron();     break;     } 8  

En este caso, las llaves evitan que el 998877766655443319 se adhiere al 9988776655544332020 , lo que lo obliga a adjuntar al Baron1 Aparentemente previsto en su lugar.

Aunque inicialmente podría parecer (o incluso ser) algo asustado, tendería a evitar el problema por completo: en lugar de una cascada de Baron2 , probablemente pondría las declaraciones para ser Impreso en algún tipo de mapa, luego solo haga una búsqueda en el mapa e imprima el valor asociado (si tiene uno) durante un tiempo determinado.

  Baron3  

Luego, el código solo busca la hora actual en Baron4 e imprime una cadena si hay una para un valor particular. Aparte: mientras he usado Baron5 aquí, es probable que no sea un buen ejemplo para emular, al nombrar la variable real, casi seguramente debe elegir un nombre que mejor refleje su función prevista; Algo así como Baron6 , por ejemplo.

También tenga en cuenta que esto hace que sea bastante fácil exportar los valores y las cadenas a un archivo de configuración en lugar de que se incrusten en el código. Si, por ejemplo, terminó queriendo traducir el programa a ruso o francés (o lo que sea) traducir estas cadenas no haría (en sí mismo), la fuerza re-compilando el código asociado. Del mismo modo, si decidió agregar o eliminar algunos de los mensajes, moverlos a un archivo de datos externo hace que este trivial haga.

Dicho esto, probablemente debería agregar que dudo que pueda localizar cualquier programa significativo sin compilar en absoluto (o sin reescribir al menos un poco del código). No obstante, mantener las cadenas como esta externa al código ayuda a mantener la tarea un poco más manejable.

 

First: I think the point @DFord makes is quite good.

Second, I think you should work on indenting your code better. In particular, the indentation of your main if/then/else chain is misleading:

        if (endTime - startTime > 1)             if (endTime - startTime == 360)                 System.out.println("6 Minutes left");             if (endTime - startTime == 300)                 System.out.println("5 Minutes left");             if (endTime - startTime == 240)                 System.out.println("4 Minutes left");             if (endTime - startTime == 180)                 System.out.println("3 Minutes left");             if (endTime - startTime == 120)                 System.out.println("2 Minutes left");             if (endTime - startTime == 60)                 System.out.println("1 Minute left");             if (endTime - startTime == 30)                 System.out.println("30 Seconds left");             if (endTime - startTime == 15)                 System.out.println("15 Seconds left");             if (endTime - startTime == 5)                 System.out.println("5 Seconds left");         else if (endTime - startTime == 1) {             System.out.println("Foo is up!"); 

When an else follows a chain of if statements like this, it attaches to the most recent if that doesn't already have an else. An if statement controls exactly one following statement (which needs to be a compound statement if you want it to control more than one syntactical statement). In other words, the code really works like:

if (endTime - startTime > 1)     if (endTime - startTime == 360)         System.out.println("6 Minutes left");  // The following are evaluated regardless of whether the `> 1` condition was met if (endTime - startTime == 300)     System.out.println("5 Minutes left"); if (endTime - startTime == 240)     System.out.println("4 Minutes left"); if (endTime - startTime == 180)     System.out.println("3 Minutes left"); if (endTime - startTime == 120)     System.out.println("2 Minutes left"); if (endTime - startTime == 60)     System.out.println("1 Minute left"); if (endTime - startTime == 30)     System.out.println("30 Seconds left"); if (endTime - startTime == 15)     System.out.println("15 Seconds left"); if (endTime - startTime == 5)     System.out.println("5 Seconds left"); else if (endTime - startTime == 1) {     System.out.println("Foo is up!"); 

Based on your indentation, you apparently wanted it to be more like this:

if (endTime - startTime > 1) {     if (endTime - startTime == 360)         System.out.println("6 Minutes left");     if (endTime - startTime == 300)         System.out.println("5 Minutes left");     if (endTime - startTime == 240)         System.out.println("4 Minutes left");     if (endTime - startTime == 180)         System.out.println("3 Minutes left");     if (endTime - startTime == 120)         System.out.println("2 Minutes left");     if (endTime - startTime == 60)         System.out.println("1 Minute left");     if (endTime - startTime == 30)         System.out.println("30 Seconds left");     if (endTime - startTime == 15)         System.out.println("15 Seconds left");     if (endTime - startTime == 5)         System.out.println("5 Seconds left"); } else if (endTime - startTime == 1) {     System.out.println("Foo is up!"); 

In this case, the braces prevent the else from attaching to the immediately previous if, forcing it to attach to the if you apparently intended instead.

Although it might initially seem (or even be) somewhat wasteful, I'd tend to avoid the issue entirely: instead of a cascade of if statements, I'd probably put the statements to be printed out into some kind of Map, then just do a lookup in the map and print out the associated value (if it has one) for a given time.

// In real code, you'll need to pick some class that implements the Map interface, // but for the moment, I'm not really concerned with which one you pick. Map<Integer, string> names;  names.put(360, "6 minutes left"); names.put(300, "5 minutes left"); //... names.put(5, "5 seconds left"); 

Then the code just looks up the current time in names and prints out a string if there is one for a particular value. Aside: while I've used names here, it's probably not a good example to emulate--when naming the real variable, you should almost certainly pick a name that better reflects its intended function; something like timeToString, for example.

Also note that this makes it fairly easy to export the values and strings to an configuration file instead of them being embedded in the code. If, for example, you ended up wanting to translate the program to Russian or French (or whatever) translating these strings wouldn't (in and of itself) force re-compiling the associated code. Likewise, if you decided to add or remove some of the messages, moving them to an external data file makes this trivial to do.

That said, I should probably add that I doubt you could localize any significant program without re-compiling at all (or without rewriting at least a little of the code). Nonetheless, keeping strings like this external to the code does help keep the task a little more manageable.

 
 
10
 
vote

Concepto:

Su concepto no es adecuado para ser utilizado en múltiples cuentas bajas, en lugar de eso, es posible que desee intentar algo como lo siguiente:

cuidado, este es un borrador en bruto!

  public class Buff{     private int respawnSeconds;     private String name;     private int respawnsAtSecond;     //constructor + getters and setters      public void kill(int currentGameSeconds){       this.respawnsAtSecond = currentGameSeconds + respawnSeconds;     } }  public class Game{     private int elapsedSeconds;     private Set<Buff> buffs;      public void start(){         elapsedSeconds = 0;         buffs.add(new Buff("friendlyBlue", 300));         //Add the other buffs     }      //You need some ticking mechanism, maybe you could use something like a while(true) }   

Sidedenotes:

Naming:

Los nombres de sus métodos son inconsistentes. Los métodos azules y rojos son camelCase , pero sus objetivos más grandes son 9988776655544332 ( 99887776655443333 , Baron4 ) Aparte de eso, usted es muy consistente con variables locales de camellas y comprensibles muy claras.

Método Responsibilites:

Haces que tus métodos hacen demasiado. Están haciendo el conteo, la impresión y los cálculos todos a la vez ... Extraer los sub-métodos y agregar parámetros para los diferentes nombres de objetivos.

 

Concept:

Your concept is not suited to be used on multiple countdowns, instead you might want to try something like the following:

Beware, this is a raw draft!

public class Buff{     private int respawnSeconds;     private String name;     private int respawnsAtSecond;     //constructor + getters and setters      public void kill(int currentGameSeconds){       this.respawnsAtSecond = currentGameSeconds + respawnSeconds;     } }  public class Game{     private int elapsedSeconds;     private Set<Buff> buffs;      public void start(){         elapsedSeconds = 0;         buffs.add(new Buff("friendlyBlue", 300));         //Add the other buffs     }      //You need some ticking mechanism, maybe you could use something like a while(true) } 

Sidenotes:

Naming:

Your method names are inconsistent.. the blue and red methods are camelCase, but your larger objectives are PascalCased (Dragon, Baron) aside from that, you are very consistent with very clear and understandable camelcased local variables.

Method Responsibilites:

You make your methods do too much. They are doing the counting, the printing and the calculations all at once... Extract sub-methods and add parameters for the different objective names.

 
 
6
 
vote

Nunca he tocado a Java, por lo que esto no puede compilar, sino que hará que su código sea un poco más corto, podría usar, además de la respuesta de DFords (dentro del bucle):

  long seconds = endTime - startTime; if (seconds == 1)     System.out.println(finalMsg); else if (seconds == 5)     System.out.println("5 Seconds left"); else if (seconds == 15)     System.out.println("15 Seconds left"); else if (seconds == 30)     System.out.println("30 Seconds left"); else if (seconds <= 240 && seconds % 60 == 0)     System.out.println(seconds/60 + " minutes left");   
 

I have never touched java, so this may not compile, but to make your code somewhat shorter, you could use, in addition to DFords answer (inside the loop):

long seconds = endTime - startTime; if (seconds == 1)     System.out.println(finalMsg); else if (seconds == 5)     System.out.println("5 Seconds left"); else if (seconds == 15)     System.out.println("15 Seconds left"); else if (seconds == 30)     System.out.println("30 Seconds left"); else if (seconds <= 240 && seconds % 60 == 0)     System.out.println(seconds/60 + " minutes left"); 
 
 
   
   
5
 
vote

@dford está completamente correcto con el evento de tiempo en un método separatly.

Todavía lo encuentro más legible cuando usa el interruptor en combinaciones con la final legible

  private static final int MINUTES_4 = 240; private static final int MINUTES_3 = 180; private static final int MINUTES_2 = 120; private static final int MINUTES_1 = 60; private static final int SECONDS_30 = 30; private static final int SECONDS_15 = 15; private static final int SECONDS_5 = 5; private static final int SECONDS_1 = 1;  private static void Countdown(long startTime, long endTime, string finalMsg){     while (System.currentTimeMillis() / 1000 < endTime) {         while (startTime != System.currentTimeMillis() / 1000) {             String message;             startTime++;             switch (endTime - startTime) {                case MINUTES_4 : message = "4 Minutes left";                break;                case MINUTES_3 : message = "3 Minutes left";                break;                case MINUTES_2 : message = "2 Minutes left";                break;                case MINUTES_1 : message = "1 Minutes left";                break;                case SECONDS_30 : message = "30 seconds left";                break;                case SECONDS_15 : message = "15 seconds left";                break;                case SECONDS_5  : message = "5 seconds left";                break;                case SECONDS_1  : message = finalMsg;                default : break;             }             if (null != message) {                 System.out.println(message);             }         }     } }   
 

@Dford is completly right with putting the time event to an seperatly method.

I still find it more readable when you use the switch in combinations with readable final's

private static final int MINUTES_4 = 240; private static final int MINUTES_3 = 180; private static final int MINUTES_2 = 120; private static final int MINUTES_1 = 60; private static final int SECONDS_30 = 30; private static final int SECONDS_15 = 15; private static final int SECONDS_5 = 5; private static final int SECONDS_1 = 1;  private static void Countdown(long startTime, long endTime, string finalMsg){     while (System.currentTimeMillis() / 1000 < endTime) {         while (startTime != System.currentTimeMillis() / 1000) {             String message;             startTime++;             switch (endTime - startTime) {                case MINUTES_4 : message = "4 Minutes left";                break;                case MINUTES_3 : message = "3 Minutes left";                break;                case MINUTES_2 : message = "2 Minutes left";                break;                case MINUTES_1 : message = "1 Minutes left";                break;                case SECONDS_30 : message = "30 seconds left";                break;                case SECONDS_15 : message = "15 seconds left";                break;                case SECONDS_5  : message = "5 seconds left";                break;                case SECONDS_1  : message = finalMsg;                default : break;             }             if (null != message) {                 System.out.println(message);             }         }     } } 
 
 
4
 
vote

Modificé su código un poco para trabajar con varias cuentas bajas ahora:

  1. Crear una entidad para tus buffs
  2. Crea un mapa con buffs
  3. usó el mapa para eliminar la declaración del interruptor en la función principal
  4. usó el mapa para hacer el menú dinámico
  5. iniciar un nuevo hilo para cada temporizador para comenzar más de un temporizador

  package test;  import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner;   public class LolTimer  {            /**List with running countdowns*/     private static List<String> countdowns = new ArrayList<String>();      /**Main function*/     public static void main(String[] args)      {         //variable instantiation         Scanner myScanner = new Scanner(System.in);          HashMap<Integer, Buff> BuffMap = creatBuffs();         int numberBuffs = BuffMap.size();         int buffID = 0;          //Print the menue with buffs etc.         System.out.println("Jungle Timers v1.0");         System.out.println(" Select a buff to time: ");         for(int i = 1; i <= numberBuffs; i++)             System.out.println(i + ". " + BuffMap.get(i).m_sName);         System.out.println(numberBuffs+1 + ". EXIT");         System.out.print(" >  ");          //loop to track as many buffs as the user want         while(buffID != numberBuffs+1)         {             buffID = myScanner.nextInt();             if(buffID > 0 && buffID <= numberBuffs)             {                 Buff buff = BuffMap.get(buffID);                 trackBuff(buff.m_nRespawnTime, buff.m_sName);             }         }          //if exit is choosen -> close scanner and exit the programm         myScanner.close();         System.exit(0);     }      /**Decide if a Buff is still running or not.*/     public static void trackBuff(int nRespawnTime, String sName)     {         if(countdowns.contains(sName))             System.out.println("This Countdown is still running.");         else          {             System.out.println(" Tracking " + sName + "...");             startThread(nRespawnTime, sName);         }     }      /**Starts new Thread with a new Countdowntimer.*/     public static void startThread(int nRespawnTime, final String sName)     {         countdowns.add(sName);          final int m_nStartTime = (int) (System.currentTimeMillis() / 1000);         final int m_nEndTime = m_nStartTime + nRespawnTime;          Thread updateThread = new Thread()          {             @Override             public void run()              {                 int curTime = m_nStartTime;                 int m_nTimeDiff = 0;                  while (System.currentTimeMillis() / 1000 < m_nEndTime)                  {                     while (curTime != System.currentTimeMillis() / 1000)                      {                         m_nTimeDiff = m_nEndTime - curTime;                         curTime += 1;                         if (m_nTimeDiff == 420)                             System.out.println(sName + ": 7 Minutes left");                         if (m_nTimeDiff == 360)                             System.out.println(sName + ": 6 Minutes left");                         if (m_nTimeDiff == 300)                             System.out.println(sName + ": 5 Minutes left");                         if (m_nTimeDiff == 240)                             System.out.println(sName + ": 4 Minutes left");                         if (m_nTimeDiff == 180)                             System.out.println(sName + ": 3 Minutes left");                         if (m_nTimeDiff == 120)                             System.out.println(sName + ": 2 Minutes left");                         if (m_nTimeDiff == 60)                             System.out.println(sName + ": 1 Minute left");                         if (m_nTimeDiff == 30)                             System.out.println(sName + ": 30 Seconds left");                         if (m_nTimeDiff == 15)                             System.out.println(sName + ": 15 Seconds left");                         if (m_nTimeDiff == 5)                             System.out.println(sName + ": 5 Seconds left");                     }                 }                  System.out.println(sName + " is up!");                 countdowns.remove(sName);                 Thread.currentThread().interrupt();             }         };         updateThread.start();      }      /**Creat all the Buffs you want. You fastly can add some Buffs(wolves, ghosts) here.*/     public static HashMap<Integer, Buff> creatBuffs()     {         HashMap<Integer, Buff> BuffMap = new HashMap<>();         BuffMap.put(1, new Buff(300, "your Blue"));         BuffMap.put(2, new Buff(300, "enemy Blue"));         BuffMap.put(3, new Buff(300, "your Red"));         BuffMap.put(4, new Buff(300, "enemy Blue"));         BuffMap.put(5, new Buff(300, "Dragon"));         BuffMap.put(6, new Buff(300, "Baron"));         return BuffMap;     } }  /**Entity for your Buffs*/ class Buff {     public int m_nRespawnTime;     public String m_sName;      public Buff(int time, String name)     {         m_nRespawnTime = time;         m_sName = name;     } }   
 

I modified your code a bit to work with several countdowns now:

  1. create an entity for your buffs
  2. create an map with buffs
  3. used the map to remove the switch statement in main function
  4. used the map to make the menu dynamic
  5. start a new thread for every timer to start more than one timer

package test;  import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner;   public class LolTimer  {            /**List with running countdowns*/     private static List<String> countdowns = new ArrayList<String>();      /**Main function*/     public static void main(String[] args)      {         //variable instantiation         Scanner myScanner = new Scanner(System.in);          HashMap<Integer, Buff> BuffMap = creatBuffs();         int numberBuffs = BuffMap.size();         int buffID = 0;          //Print the menue with buffs etc.         System.out.println("Jungle Timers v1.0");         System.out.println("\nSelect a buff to time:\n");         for(int i = 1; i <= numberBuffs; i++)             System.out.println(i + ". " + BuffMap.get(i).m_sName);         System.out.println(numberBuffs+1 + ". EXIT");         System.out.print("\n>  ");          //loop to track as many buffs as the user want         while(buffID != numberBuffs+1)         {             buffID = myScanner.nextInt();             if(buffID > 0 && buffID <= numberBuffs)             {                 Buff buff = BuffMap.get(buffID);                 trackBuff(buff.m_nRespawnTime, buff.m_sName);             }         }          //if exit is choosen -> close scanner and exit the programm         myScanner.close();         System.exit(0);     }      /**Decide if a Buff is still running or not.*/     public static void trackBuff(int nRespawnTime, String sName)     {         if(countdowns.contains(sName))             System.out.println("This Countdown is still running.");         else          {             System.out.println("\nTracking " + sName + "...");             startThread(nRespawnTime, sName);         }     }      /**Starts new Thread with a new Countdowntimer.*/     public static void startThread(int nRespawnTime, final String sName)     {         countdowns.add(sName);          final int m_nStartTime = (int) (System.currentTimeMillis() / 1000);         final int m_nEndTime = m_nStartTime + nRespawnTime;          Thread updateThread = new Thread()          {             @Override             public void run()              {                 int curTime = m_nStartTime;                 int m_nTimeDiff = 0;                  while (System.currentTimeMillis() / 1000 < m_nEndTime)                  {                     while (curTime != System.currentTimeMillis() / 1000)                      {                         m_nTimeDiff = m_nEndTime - curTime;                         curTime += 1;                         if (m_nTimeDiff == 420)                             System.out.println(sName + ": 7 Minutes left");                         if (m_nTimeDiff == 360)                             System.out.println(sName + ": 6 Minutes left");                         if (m_nTimeDiff == 300)                             System.out.println(sName + ": 5 Minutes left");                         if (m_nTimeDiff == 240)                             System.out.println(sName + ": 4 Minutes left");                         if (m_nTimeDiff == 180)                             System.out.println(sName + ": 3 Minutes left");                         if (m_nTimeDiff == 120)                             System.out.println(sName + ": 2 Minutes left");                         if (m_nTimeDiff == 60)                             System.out.println(sName + ": 1 Minute left");                         if (m_nTimeDiff == 30)                             System.out.println(sName + ": 30 Seconds left");                         if (m_nTimeDiff == 15)                             System.out.println(sName + ": 15 Seconds left");                         if (m_nTimeDiff == 5)                             System.out.println(sName + ": 5 Seconds left");                     }                 }                  System.out.println(sName + " is up!");                 countdowns.remove(sName);                 Thread.currentThread().interrupt();             }         };         updateThread.start();      }      /**Creat all the Buffs you want. You fastly can add some Buffs(wolves, ghosts) here.*/     public static HashMap<Integer, Buff> creatBuffs()     {         HashMap<Integer, Buff> BuffMap = new HashMap<>();         BuffMap.put(1, new Buff(300, "your Blue"));         BuffMap.put(2, new Buff(300, "enemy Blue"));         BuffMap.put(3, new Buff(300, "your Red"));         BuffMap.put(4, new Buff(300, "enemy Blue"));         BuffMap.put(5, new Buff(300, "Dragon"));         BuffMap.put(6, new Buff(300, "Baron"));         return BuffMap;     } }  /**Entity for your Buffs*/ class Buff {     public int m_nRespawnTime;     public String m_sName;      public Buff(int time, String name)     {         m_nRespawnTime = time;         m_sName = name;     } } 
 
 
3
 
vote

Si estamos hablando de la encapsulación de clase adecuada o lo que sea, aquí está mi camino por encima de la versión de lo que podría hacer.

Además, soy un programador C #, por lo que parte de la sintaxis puede estar un poco apagada, pero he hecho un esfuerzo al menos para usar Java correcto.

  • Mantenga sus indicaciones de consola en el método principal
  • Crear un enum que representa a sus diferentes tipos de temporizadores
  • Cree lo que es esencialmente solo una clase de repositorio de datos que sostiene sus cadenas (como "seguimiento del azul enemigo ...") y otros valores constantes (como su 300 que se agrega al temporizador).
    • usa nombres significativos. Todo es definitivo estático. Algo como la respuesta de @ chillworld.
    • Llámelo algo como los concentristas globales, o lo que sea significativo para usted.
  • Crear una clase que sea responsable de administrar su temporizador (llame a su rastreador o algo. Lo que sea.). Esta clase incluiría:
    • un constructor que toma el enumio mencionado anteriormente como un parámetro
    • Un campo privado para almacenar localmente dijo Enum
    • Método de cuenta regresiva (desde la respuesta de @ dford) mezclada con la optimización de la respuesta de @ lennart_96
    • Un método de inicialización para establecer sus valores de temporizador y, en base, en función del valor enumio local, y llamar a un método separado para mostrar su mensaje de cuenta regresiva inicial, también basado en el valor enumio.

Al final, terminarías con algo como:

  public enum TimerType {     FriendlyBlue, EnemyBlue... }  public class MainProgram {     private TimerType tType;     public static void main(String[] args) {         // Do your console prompts          // Assign the timer type         switch (timerChoice) {             case 1: tType = TimerType.FriendlyBlue; break;             case 2: ...         }          // Create the tracker object and kick off the timer         new Tracker(tType);     } }  public class Tracker {     private TimerType tType;     private string initialTrackingMessage;     ...      public Tracker(TimerType timerType) {         tType = timerType;         InitializeTracker();         CountDown();     }      private void InitializeTracker() {         initialTrackingMessage = GetInitialTrackingMessageForTrackingType();         // Initialize any other variables          DisplayMessage(initialTrackingMessage);     }      private string GetInitialTrackingMessageForTrackingType() {         string returnMessage;         switch (tType) {             case FriendlyBlue: returnMessage = GlobalConstants.TRACKING_BLUE; break;             ...         }         return returnMessage;     }      private void DisplayMessage(string message) {         System.out.println(message);         // Any other logic you want to do     }      private void CountDown() {         // Your countdown logic here     } }  public static class GlobalConstants() {     // Messages     public static final string TRACKING_BLUE = "Tracking your blue..."     ...      // Values     public static final int INITIAL_TIMER_LENGTH = 300; }   

Estoy seguro de que notaste que me gusta usar palabras completas en mi codificación. Es realmente agradable para las personas que tienen que mantener su código cuando se ha ido. También podría agregar fácilmente un método 998877666655443399 o algo que se ocupe de la inicialización y la cuenta regresiva, si no le gusta la idea de hacerlo todo del constructor.

Si termina agregando más detalles a cada tipo de temporizador, este enfoque hace que sea mucho más fácil convertir su clase central en una clase abstracta, o incluso una interfaz, según corresponda. Tal vez incluso ambos. El método camelCase06655443310 sería apropiado para una clase abstracta, pero el método 998877665554443311 puede ser más apropiado para una interfaz, a menos que necesite una implementación predeterminada. Además, los métodos y tipos (clases, enumeras) realizan una sola función, que es un pilar importante del buen diseño OO.

editar

Como beneficio adicional (y para abordar su problema secundario), puede rastrear fácilmente los múltiples buffs con este enfoque, manteniendo una colección de objetos de rastreador.

 

If we're talking proper class encapsulation or whatever, here's my way over-engineered version of what you could do.

Also, I'm a C# programmer, so some of the syntax may be a little off, but I've made some effort at least to use correct Java.

  • Keep your console prompts in the Main method
  • Create an enum that represents your different types of timers
  • Create what is essentially just a data repository class that holds your strings (like "Tracking enemy blue...") and other constant values (like your 300 that gets added to the timer).
    • Use meaningful names. Everything is static final. Something like @chillworld's answer.
    • Call it something like GlobalConstants, or whatever is meaningful to you.
  • Create a class that is responsible for managing your timer (call it Tracker or something. whatever.). This class would include:
    • A constructor that takes the above mentioned enum as a parameter
    • A private field to locally store said enum
    • Countdown method (from @DFord's answer) mixed with the optimization from @Lennart_96's answer
    • An initialize method to set your timer values and such based on the local enum value, and call a separate method to display your initial countdown message, also based on the enum value.

In the end you'd end up with something like:

public enum TimerType {     FriendlyBlue, EnemyBlue... }  public class MainProgram {     private TimerType tType;     public static void main(String[] args) {         // Do your console prompts          // Assign the timer type         switch (timerChoice) {             case 1: tType = TimerType.FriendlyBlue; break;             case 2: ...         }          // Create the tracker object and kick off the timer         new Tracker(tType);     } }  public class Tracker {     private TimerType tType;     private string initialTrackingMessage;     ...      public Tracker(TimerType timerType) {         tType = timerType;         InitializeTracker();         CountDown();     }      private void InitializeTracker() {         initialTrackingMessage = GetInitialTrackingMessageForTrackingType();         // Initialize any other variables          DisplayMessage(initialTrackingMessage);     }      private string GetInitialTrackingMessageForTrackingType() {         string returnMessage;         switch (tType) {             case FriendlyBlue: returnMessage = GlobalConstants.TRACKING_BLUE; break;             ...         }         return returnMessage;     }      private void DisplayMessage(string message) {         System.out.println(message);         // Any other logic you want to do     }      private void CountDown() {         // Your countdown logic here     } }  public static class GlobalConstants() {     // Messages     public static final string TRACKING_BLUE = "Tracking your blue..."     ...      // Values     public static final int INITIAL_TIMER_LENGTH = 300; } 

I'm sure you noticed that I like to use whole words in my coding. It's really nice for people who have to maintain your code when you're gone. You could also easily add a Start() method or something that takes care of the initialization and countdown, if you don't like the idea of doing it all from the constructor.

If you end up adding more details to each type of timer, this approach makes it much easier to convert your core class into an abstract class, or even an interface, as appropriate. Maybe even both. The Countdown method would be appropriate for an abstract class, but the InitializeTracker method might be more appropriate for an interface, unless you need a default implementation. Also, the methods and types (classes, enums) each perform only one function, which is an important pillar of good OO design.

EDIT

As an additional benefit (and to address your secondary issue), you can easily track multiple buffs with this approach, by keeping a collection of Tracker objects.

 
 
0
 
vote

Permítanme simplemente abordar su segmento "repetitivo" en el que se le ocurre muchos minutos. Algunas matemáticas simples pueden recortar el tamaño de esos bloques:

  int secLeft = endTime - startTime; int minsLeft = secLeft/60; if( secLeft % 60 == 0 ) // only happens at multiples of 60, eg 0,60,120,180.. {     // Message of form "2 minutes left"     String msg = Integer.toString(minsLeft) + " Minutes left"; } else if( secLeft == 30 ) {     // need special cases for the smaller values }   
 

Let me just address your "repetitive" segment where you check how many minutes are left.. some simple math can trim down the size of those blocks:

int secLeft = endTime - startTime; int minsLeft = secLeft/60; if( secLeft % 60 == 0 ) // only happens at multiples of 60, eg 0,60,120,180.. {     // Message of form "2 minutes left"     String msg = Integer.toString(minsLeft) + " Minutes left"; } else if( secLeft == 30 ) {     // need special cases for the smaller values } 
 
 

Relacionados problema

19  Plantilla de cronómetro  ( Stopwatch template ) 
A menudo es útil poder el código de tiempo, por ejemplo, para evaluar enfoques alternativos al mismo problema. Debido a que esto es algo que utilizo con frecu...

3  Linux C ++ Timer Class: ¿Cómo puedo mejorar la precisión?  ( Linux c timer class how can i improve the accuracy ) 
Escribí esta clase hoy, pero estoy tratando de averiguar cómo hacerlo más preciso. Paso en segundos y multiplico por 1000 para hacerlo milisegundos, y el tiem...

4  Salida de una cuenta regresiva en un div  ( Outputting a countdown in a div ) 
Obtuve este código trabajando con el complemento de cuenta regresiva jQuery para tomar una entrada y salida una cadena cuenta regresiva en un div. ¿Hay una ...

5  Resumen de la suite de prueba para una simple evaluación de desempeño en Java  ( Abstracting test suite for simple performance evaluation in java ) 
Hoy, me senté para escribir una pequeña prueba de rendimiento para evaluar rápidamente una corazonada que tuvo con respecto a una optimización. El código resu...

4  Aplicación de la consola de temporizador de aceleración  ( Speed cubing timer console application ) 
Este código es mi primera implementación de este estilo de aplicación en la consola. En esencia, un cronómetro con alguna funcionalidad agregada. Estaba int...

2  Temporizador en JavaScript  ( Timer in javascript ) 
Esta es mi primera aplicación de JavaScript (está inspirada en este temporizador ). ¿Cómo podría mejorarlo? Tuve que establecer el #include <iostream> usi...

3  JavaScript: función del temporizador  ( Javascript timer function ) 
Esta es una función que hice para un temporizador que cuenta hacia abajo y realiza una devolución de llamada al final. Parece que funciona bien, pero creo que...

4  Helper Utilities para una evaluación comparativa más fácil en C  ( Helper utilities for easier benchmarking in c ) 
Tengo esta pequeña biblioteca para medir el tiempo de ejecución en milisegundos y devolver la duración más el resultado: execres.h X4 execres.c ...

4  Dormir con la pantalla cuenta abajo  ( Sleep with count down display ) 
Tengo una función de sueño que muestra el tiempo restante en la SEC, se apreciarían algunos comentarios this9 Este código y actualizaciones están dispon...

4  Temporizador de eventos Base de datos Capa de interacción  ( Event timers database interaction layer ) 
Acabo de empezar con los conceptos básicos de OOP. Al principio, se veía complicado, pero una vez que acaba de empezar, parecía tan fácil y todo parece funcio...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos