2011-02-28 9 views
10

Quiero hacer un cambio en el ciclo while donde al final de cada instrucción switch el ciclo while se detiene y solicitar una entrada como F, R, C, Q. la siguiente declaración funciona pero la declaración no se rompe. Por favor, ayudacómo establecer una instrucción switch en el ciclo while en java

public static void main(String[] args) throws IOException { 

    // start both with 1 point 
    int goodTotal = 50; 
    int monTotal = 50; 

    // input switch statement 

    while (goodTotal > 0 && monTotal > 0) { 

     System.out.print("Type a letter: "); 
     System.out.println("\n"); 
     System.out.print("F: Go out and Fight "); 
     System.out.println("\n"); 
     System.out.print("R: Rest "); 
     System.out.println("\n"); 
     System.out.print("C: Check Stats "); 
     System.out.println("\n"); 
     System.out.print("Q: Quit "); 
     int input = System.in.read(); 

     System.out.println("You typed: " + (char) input); 

     switch (input) { 
     case 'f': 
      System.out.println("Continue the game"); 
      break; 
     case 'r': 
      System.out.println("Players should rest"); 
      break; 
     case 'c': 
      System.out.println("Checking the status of the game"); 
      System.out.print("Goodman has " + goodTotal + " points and Monster has " + monTotal + " points"); 
      System.out.println("\n"); 
      break; 
     case 'q': 
      System.out.println("Game over"); 
      System.exit(input); 
      break; 
     default: 
      System.out.println("Invalid selection"); 
      break; 
     } 

     // Set value of minimum and maximum damage 
     int minDmg = 2; 
     int maxDmg = 15; 

     // Get random number; 
     int damage = minDmg + Double.valueOf(Math.random() * (maxDmg - minDmg)).intValue(); 
     int damage2 = minDmg + Double.valueOf(Math.random() * (maxDmg - minDmg)).intValue(); 

     // remove value of damage from started value to get total value remaining 
     goodTotal = goodTotal - damage; 
     monTotal = monTotal - damage2; 

     // print message if still in the game 
     if (goodTotal > 0) { 
      System.out.println("Goodman has " + goodTotal + " points left. Not bad, Man! "); 
     } 

     // if Goodman survives round 2 print a message of encouragement 
     if (goodTotal > 0 && count > 1 && count <= 2) { 
      System.out.print("This is encouraging. Goodman has lasted past roundhh " + count + ". "); 

      // print new message if Goodman passes round 3 
     } else if (goodTotal > 0 && count == 3) { 
      System.out.print("Goodman is as strong as Samson. He has lasted round " + count 
        + " and still looks strong."); 
      System.out.print(" 10 hit points has been added to your total"); 
     } 

     if (monTotal > 0) { 
      System.out.println("Wait, Monster has a total of " + monTotal + " points and is still in the game"); 
     } 

     // exit if have less than 0 point, and print game over. Congratulate the winner 
     if (goodTotal < 0) { 
      System.out.println("Goodman you are out of the game"); 
      System.out.println("The monster will take over the village. This is sad"); 
      System.out.println("Game Over!"); 
     } else if (monTotal < 0) { 
      System.out.println("Goodman has been victorious"); 
      System.out.println("The monster is dead. The people live!!!!"); 
      System.out.println("Game Over!"); 
     } 
     System.out.println("This is the end of round " + count + " "); 
     System.out.println("\n"); 
     count = count + 1; 

    } 

} 
+1

Utilice el formato del código. – Mudassir

+0

La interrupción de cada interruptor nunca ejecutará el código después del cambio (hasta el final del tiempo). ¿Es eso lo que quieres lograr? – aldrin

Respuesta

19

Uso una etiqueta en el bucle:

loop: while (goodTotal > 0 && monTotal > 0) { 
    // ... 
    switch (input) { 
     case 'f': 
      // ... 
      break loop; 
     case 'r': 
      // ... 
      break loop; 
     // ... 
    } 
    // ... 
} 
6

Debe utilizar labelled breaks.

Aunque probablemente es mejor volver a escribir el código de una manera que no les es necesario, ya que no son muy fáciles de leer.

1

input es de tipo int , pero las etiquetas de casos son caracteres literales (es decir, f,r,c,q). ¿Por qué no solo hace que el input también sea de tipo char?

char input = System.in.read(); 
+0

Laurent y Mahesh, muchas gracias. funciona – earnest

+0

@earnest De nada. Por favor vote y/o acepte la respuesta que considere apropiada. –

+0

Chicos, tengo una pregunta de seguimiento. Por favor, ayuda Quiero agregar estas opciones, donde GoodMan y comprar un bate, hacha o espada para luchar contra el monstruo. Cómo configuro estas opciones variables en matrices 0. Bat min damage = 2 max damage = 4 cost = 3 1. ax min damage = 4 max damage = 6 cost = 6 2. sword min damage = 6 daño máximo = 8 costo = 10 3. cancelar – earnest

Cuestiones relacionadas