2016-04-25 3 views
0

私は、私がユーザに尋ねている船のリストを循環させようとしています。すでにwhileループがあります。 2番目のループを外側に追加すると、2番目のループが1回実行された後にフリーズします。中にループ中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

いくつかの書式を使用してください! – shmosel

+0

あなたはそれが凍っているとはどういう意味ですか?エラーメッセージはありますか? – sebenalern

答えて

4

これは、プログラムの流れは、毎elseステートメントに入る3にvalidを増加させ、次いで、アウターwhile(index != 4)ループ内無限ループし続けることを意味します。

外側のwhileの状態でチェックされた値は決して編集されないので、常に0の初期値に等しいことに注意してください。そのため、プログラムはwhile whileループテストを無限に通過し、終了しません。