2016-04-25 14 views
0

Ich versuche, durch die Liste der Schiffe zu radeln, die ich den Benutzer frage. Es gibt bereits eine While-Schleife. Nachdem ich das zweite auf der Außenseite hinzugefügt habe, friert es nach einem Durchlauf der zweiten Schleife ein.While Loop innerhalb While (Java) Battleship Game

Scanner sc = new Scanner(System.in); 
String playerName; 
int uInput; 
public static String[] names = {"DESTROYER","SUBMARINE","CRUISER","BATTLESHIP","AIRCRAFT"}; 
public static int[] shipL = {2, 3, 3, 5, 6 }; 

public static void shipSetup() 
{ 
    Scanner sc = new Scanner(System.in); 
    String input = " "; 
    int valid = 0; 
    int index = 0; 
    while(index != 4){ 
    while (valid !=3){ 
     System.out.println("Place " + names[index] + " ("+ shipL[index]+ " spaces - Format: Coordinate #1, Coordinate #2, Direction)"); 
     input = sc.nextLine(); 
     String[] inputArray; 
     inputArray = input.split(","); 
     //3 values errors 
     if(inputArray.length != 3){System.out.println("ERROR:Invalid Direction");continue;} 
     try{ 
      char z = inputArray[2].charAt(0); 
      int x = Integer.parseInt(inputArray[0]); 
      int y = Integer.parseInt(inputArray[1]); 
      //resets loop 
      valid = 0; 
      //Input direction errors 
      if(z != 'V' && z != 'H'){ 
      System.out.println("ERROR:Invalid Direction - Vertical|V| or Horizontal|H|"); 
      } 
      else{ 
      ++valid; 
      } 
      //Input cord errors 
      if(x > 9 || x < 0){ 
      System.out.println("ERROR:Invalid Coordinate - Coordinate must be 1 - 9"); 
      } 
      else{ 
      ++valid; 
      } 
      if(y > 9 || y < 0){ 
      System.out.println("ERROR:Invalid Coordinate - Coordinate must be 1 - 9"); 
      } 
      else{ 
      ++valid; 
      } 
     } catch(NumberFormatException e){ 
      System.out.println("ERROR: Coordinate are numbers dumbASS"); 
     } 
     } 
    } 
    } 
+3

BITTE formatieren! – shmosel

+0

Was meinst du es friert ein? Gibt es eine Fehlermeldung? – sebenalern

Antwort

4

Es bedeutet, dass der Programmablauf jede else Anweisung eingibt, erhöht valid bis 3, und dann in einer Schleife weiter stufenlos innerhalb der äußeren while(index != 4) Schleife.

Bitte beachten Sie, dass der index Wert in äußeren while Zustand nie bearbeitet wird, daher ist es immer gleich 0. Deshalb besteht Ihr Programm den äußeren While-Loop-Test unendlich, und beendet es nie.