2013-09-22 6 views
0

영화 <치히로의 도둑>에서 치치로의 그림을 움직이는 프로그램을 쓰고 있습니다. 현재 내가해야 할 일은 그녀를 왼쪽, 오른쪽, 위, 아래로 움직이는 것입니다. 그녀는 사용자가 입력하는 초기 위치를가집니다. 그런 다음 내 프로그램에서 사용자 입력을 통해 u/d/l/r을 이동하도록 요청합니다. 사용자 입력을 다시 요청하는 메시지를 어떻게 표시합니까? 그것은 항상 그녀를 움직이고 루프를 빠져 나갑니다.스위치 설명 및 사용자 입력

// Initial position 
Scanner keyboard = new Scanner(System.in); 
System.out.print("Starting row: "); 
int currentRow = keyboard.nextInt(); 
System.out.print("Starting column: "); 
int currentCol = keyboard.nextInt(); 

// Create maze 
Maze maze = new Maze(numberRows, numberCols, currentRow, currentCol); 

System.out.print("Move Chichiro (u/d/lr): "); 

char move = keyboard.next().charAt(0); 

switch (move){ 

    case 'u': maze.moveTo(--currentRow, currentCol); // move up 
     break; 
    case 'd': maze.moveTo(++currentRow, currentCol); // move down 
     break; 
    case 'l': maze.moveTo(currentRow, --currentCol); // move left 
     break; 
    case 'r': maze.moveTo(currentRow, ++currentCol); // move right 
     break; 
    default: System.out.print("That is not a valid direction!"); 

} 
+1

당신은 네브라스카 'switch-case'를 둘러싼 do-while 루프를 만들었습니다. –

답변

1

은 한 동안 루프에 코드를 삽입하고, q 키 치는처럼, 종료 할 수있는 수단을 포함한다 : 당신은 당신이 원하는만큼 이동할 수 있습니다 다음 코드로

boolean quit=false; 

//keep asking for input until a 'q' is pressed 
while(! quit) { 
    System.out.print("Move Chichiro (u/d/l/r/q): "); 
    char move = keyboard.next().charAt(0);  

    switch (move){ 
    case 'u': maze.moveTo(--currentRow, currentCol); // move up 
       break; 
    case 'd': maze.moveTo(++currentRow, currentCol); // move down break; 
    case 'l': maze.moveTo(currentRow, --currentCol); // move left 
       break; 
    case 'r': maze.moveTo(currentRow, ++currentCol); // move right 
       break; 
    case 'q': quit=true; // quit playing 
       break; 
    default: System.out.print("That is not a valid direction!");}} 
    } 
} 
0

을 때 당신을 프로그램을 종료하려면, 당신은 단지 'Q'를 입력 할 필요가 :

 // Create maze 
    Maze maze = new Maze(numberRows, numberCols, currentRow, currentCol); 
    char move; 


    do{ 

      System.out.print("Move Chichiro (u/d/lr): "); 

     move = keyboard.next().charAt(0); 

     switch (move){ 

      case 'u': maze.moveTo(--currentRow, currentCol); // move up 
       break; 
      case 'd': maze.moveTo(++currentRow, currentCol); // move down 
       break; 
      case 'l': maze.moveTo(currentRow, --currentCol); // move left 
       break; 
      case 'r': maze.moveTo(currentRow, ++currentCol); // move right 
       break; 
      default: System.out.print("That is not a valid direction!"); 

     } 

    }while(move != 'q'); 

편집 : 수정

+0

네, 고마워요. – SegFault