2014-03-07 2 views
-1

Я не уверен, что происходит, но в консоли у меня есть красный квадрат «стоп», который я могу нажать, чтобы остановить запуск моей программы (Eclipse IDE), и моя программа просто запущена, а квадрат остается красным ..?Программа никогда не заканчивается

EDIT:

мой лабиринт:

WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW 
WSOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOWOOOOOOW 
WWOOOOOOOOOOOOOWWWWWWWWWWWWWOOOOOOOOOOWWWWWWWWWWWWWOOOOOOW 
WWWWWWOOOOOOOOOOOOWWWWWWWOOOOOOOOOOOOWWWWWWWWWWWWWWWWOOOOW 
WOOOOOOWWWWWWWWWWWWWWOOOOOOOOOOOWWWWWWWWOOOOOOOOOOOOOOOWWW 
WOOOOWWWWWWWOOOOOOWWWWOOOOOOWWWWWWWWWWWOOOOWWWWWWWWWOWWWWW 
WOOOWWWWWWWWWWWWOOWWWWWWWWWWWWOOOOOOOOOOOOWWWWWWWWWOOOOOWW 
WOOWWWWWWWWWWWWWOOWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWWOOOW 
WOWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWOOW 
WOWWWWWWWWWWWWWOOOOOOOOOOOOOOOOOOOOOOOOOOOOWWWWWWWWWWWWOOW 
WOOOOOOOOOOOOOOOOWWWWOOOOOOOOWWWWWWWOOOOOOWWWWWWWWWWWWWWFW 
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW 

EDIT: Вот мой код:

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.HashSet; 
import java.util.Scanner; 
import java.util.Stack; 
import java.awt.Point; 

public class MazeExplorer { 
    static Point startPoint = new Point(); 
    static Point finishPoint = new Point(); 
    final static int mazeHeight = 12; 
    final static int mazeWidth = 58; 
    static char[][] mazePoints = new char[mazeHeight][mazeWidth]; 
    Stack<Point> pointsNotTraversed = new Stack<Point>(); 
    Point pt = new Point(); 
    static HashSet<Point> previousLocations = new HashSet<Point>(); 
    static Stack<Point> nextPoints = new Stack<Point>(); 

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

     System.out.println("Please enter the file name of your Maze"); 
     Scanner console = new Scanner(System.in); 
     File f = new File(console.nextLine()); 
     Scanner sc = new Scanner(f); 

     if(!sc.hasNextLine()){ 
      System.out.println("Sorry, please enter a file name with the extension, that contains a maze!"); 
     } 
     System.out.println("So, you want to know if your maze is solvable.....?"); 

     for (int row = 0; row < mazeHeight && sc.hasNext(); row++) { 
      final String mazeRow = sc.next(); //Get the next row from the scanner. 
      mazePoints[row] = mazeRow.toCharArray(); //Convert the row into a char[]. 
     } 
      //identify the finish point 
     for(int i = 0; i < mazeHeight; i++){ 
      for(int j = 0; j<mazeWidth; j++){ 
       if(mazePoints[i][j] == 'F'){ 
        finishPoint = new Point(i, j); 
       }  
      } 
     } 
     // Identify the start point 
     for(int i = 0; i< mazeHeight; i++){ 
      for(int j = 0; j < mazeWidth; j++){ 
       if(mazePoints[i][j] == 'S'){ 
       startPoint = new Point(i , j); 
       } 
      } 
     } 
     isTraversable(startPoint);  
    } 
     public static boolean isTraversable(Point current){ 
      boolean isSolvable = false; 
      nextPoints.push(current); 

      do { 


       if(current.y < 11) { 
        if((mazePoints[current.y + 1][current.x] != ' ') && (mazePoints[current.y + 1][current.x] != 'W')){ // below direction 
        nextPoints.push(new Point(current.y + 1, current.x)); 
        mazePoints[current.y + 1][current.x] = ' ';   
        isTraversable(nextPoints.pop());  

       } 
       } 
       if(current.y > 0){ 


       if (mazePoints[current.y - 1][current.x] != ' ' && mazePoints[current.y - 1][current.x] != 'W'){ //up dir 
        nextPoints.push(new Point(current.y - 1, current.x)); 
        mazePoints[current.y - 1][current.x] = ' '; //'X' marks where you've already been 
        isTraversable(nextPoints.pop());  

       } 
       } 
       if(current.x < 57){ 
       if(mazePoints[current.y][current.x + 1] != ' ' && mazePoints[current.y][current.x + 1] != 'W'){ // to the right 
        nextPoints.push(new Point(current.y, current.x + 1)); 
        mazePoints[current.y][current.x + 1] = ' '; 
        isTraversable(nextPoints.pop());  

       } 
       } 
       if(current.x > 0){ 


       if(mazePoints[current.y][current.x - 1] != ' ' && mazePoints[current.y][current.x - 1] != 'W') { // to the left 
        nextPoints.push(new Point(current.y, current.x - 1)); 
        mazePoints[current.y][current.x - 1] = ' ';  
        isTraversable(nextPoints.pop());  

       } 
       } 
       if(current.equals(finishPoint)){ 
        isSolvable = true; 
        System.out.println("MAZE IS SOLVABLE, YAHOOOOOO!!!!"); 
       } 




      } while(!current.equals('F') && !nextPoints.isEmpty());  


      return isSolvable;   
     } 
} 
+0

Очень, очень расплывчатый. Если вы считаете, что это из-за вашего кода, добросердечно напишите свой код здесь. Если он сохраняется с любым кодом, то для этого лучше всего перейти на SuperUser, а не в SO. – Manhattan

+0

Ну, у вас есть какой-то бесконечный цикл? Какова ваша программа? – Kyranstar

+0

Вы вставили случайный фрагмент кода и заявили, что ваша программа не выходит. Этого недостаточно. –

ответ

1

Как я уже говорил ранее, вам просто нужно перенастроить рекурсивный метод. Я взял на себя смелость сделать это, но если вы когда-нибудь захотите узнать, как программировать, вам захочется попробовать и решить такие проблемы самостоятельно. Или попробуйте понять логику вашего решения, прежде чем начинать кодирование.

Основная проблема заключается в том, что вы не знаете, в каком направлении вы хотите использовать метод, прежде чем просто вскочить, и это вызывает всевозможные ошибки, при этом разные вещи несовместимы друг с другом.

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.HashSet; 
import java.util.Scanner; 
import java.util.Stack; 
import java.awt.Point; 

public class TestCode { 
    static Point startPoint = new Point(); 
    static Point finishPoint = new Point(); 
    final static int mazeHeight = 12; 
    final static int mazeWidth = 58; 
    static char[][] mazePoints = new char[mazeHeight][mazeWidth]; 
    Stack<Point> pointsNotTraversed = new Stack<Point>(); 
    Point pt = new Point(); 
    static HashSet<Point> previousLocations = new HashSet<Point>(); 
    static Stack<Point> nextPoints = new Stack<Point>(); 

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

    System.out.println("Please enter the file name of your Maze"); 
    Scanner console = new Scanner(System.in); 
    File f = new File(console.nextLine()); 
    Scanner sc = new Scanner(f); 

    if(!sc.hasNextLine()){ 
     System.out.println("Sorry, please enter a file name with the extension, that contains a maze!"); 
    } 
    System.out.println("So, you want to know if your maze is solvable.....?"); 

    for (int row = 0; row < mazeHeight && sc.hasNext(); row++) { 
     final String mazeRow = sc.next(); //Get the next row from the scanner. 
     mazePoints[row] = mazeRow.toCharArray(); //Convert the row into a char[]. 
    } 
     //identify the finish point 
    for(int i = 0; i < mazeHeight; i++){ 
     for(int j = 0; j<mazeWidth; j++){ 
      if(mazePoints[i][j] == 'F'){ 
       finishPoint = new Point(i, j); 
      }  
     } 
    } 
    // Identify the start point 
    for(int i = 0; i< mazeHeight; i++){ 
     for(int j = 0; j < mazeWidth; j++){ 
      if(mazePoints[i][j] == 'S'){ 
      startPoint = new Point(i , j); 
      } 
     } 
    } 
    System.out.println(isTraversable(startPoint));  
} 
    public static boolean isTraversable(Point current){ 

     mazePoints[current.x][current.y] = ' '; 

     if(current.y < 56 && current.y > 0 && current.x > 0 && current.x < 11){ 
      if (mazePoints[current.x - 1][current.y] == 'O'){ // Up dir 
       Point upPoint = new Point(current.x-1, current.y); 
       nextPoints.push(upPoint); 
      } 

      if(mazePoints[current.x+1][current.y] == 'O'){ // Down dir 
       Point downPoint = new Point(current.x+1, current.y); 
       nextPoints.push(downPoint); 
      } 

      if(mazePoints[current.x][current.y + 1] == 'O'){ // to the right 
       Point rightPoint = new Point(current.x, current.y+1); 
       nextPoints.push(rightPoint); 
      } 

      if(mazePoints[current.x][current.y - 1] == 'O'){ // to the left 
       Point leftPoint = new Point(current.x, current.y-1); 
       nextPoints.push(leftPoint); 
      } 

      if(mazePoints[current.x - 1][current.y] == 'F' || 
       mazePoints[current.x + 1][current.y] == 'F' || 
       mazePoints[current.x][current.y - 1] == 'F' || 
       mazePoints[current.x][current.y + 1] == 'F'){ 
       System.out.println("MAZE IS SOLVABLE, YAHOOOOOO!!!!"); 
       return true; 
      } 

     } 
     if(nextPoints.isEmpty()){ 
      return false; 
     } 
     else{ 
      current = nextPoints.pop(); 
     } 

     return(isTraversable(current)); 

    } 
} 

С входом лабиринте:

WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW 
WSOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOWOOOOOOW 
WWOOOOOOOOOOOOOWWWWWWWWWWWWWOOOOOOOOOOWWWWWWWWWWWWWOOOOOOW 
WWWWWWOOOOOOOOOOOOWWWWWWWOOOOOOOOOOOOWWWWWWWWWWWWWWWWOOOOW 
WOOOOOOWWWWWWWWWWWWWWOOOOOOOOOOOWWWWWWWWOOOOOOOOOOOOOOOWWW 
WOOOOWWWWWWWOOOOOOWWWWOOOOOOWWWWWWWWWWWOOOOWWWWWWWWWOWWWWW 
WOOOWWWWWWWWWWWWOOWWWWWWWWWWWWOOOOOOOOOOOOWWWWWWWWWOOOOOWW 
WOOWWWWWWWWWWWWWOOWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWWOOOW 
WOWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWOOW 
WOWWWWWWWWWWWWWOOOOOOOOOOOOOOOOOOOOOOOOOOOOWWWWWWWWWWWWOOW 
WOOOOOOOOOOOOOOOOWWWWOOOOOOOOWWWWWWWOOOOOOWWWWWWWWWWWWWOFW 
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW 

дает следующий результат:

So, you want to know if your maze is solvable.....? 
MAZE IS SOLVABLE, YAHOOOOOO!!!! 
true 

Я импортирован файл другой путь, но вы можете изменить, что обратно в любой метод вы используете ранее.

+0

Это нужно вызвать в основном методе с переданной точкой начала? – bazookyelmo

+0

да. Я сделал это в заявлении на печать 'System.out.println (isTraversable (startPoint));' – leigero

+0

Это напечатает «true», а также строку «yahoooo», которую вы написали в методе. – leigero

1

Может быть, что вы начали несколько программ, и у вас есть «Показать консоли Когда стандартные изменения выпуска «Не уверены, но это объясняет один сценарий. Если вы запустите диспетчер задач и найдите там программу, вы можете попробовать завершить ее таким образом.

+0

Пробовал это, все еще идет бесконечно .... – bazookyelmo

+1

Извинения, но угадайте, не получается. Это лучше подходит вместо комментария. – Manhattan

+1

Я бы сделал этот комментарий, если бы у меня было достаточно репутации :) Длинный выстрел, но это мог быть ответ! –

0

Если он застрял и никогда не завершен, вы можете попробовать запустить свою программу в отладчике Eclipse без каких-либо контрольных точек.

Откройте вкладку «Отладка» (откройте вкладку «Из окна»> «Показать представление»> «Отладка»), приостановите поток, щелкнув правой кнопкой мыши «Thread [main] (Running)» и выбрав «Suspend».

Затем прокладывайте себе путь со дна стека, надеюсь, это будет сузить его достаточно, чтобы вы могли найти, где он блокируется.

+0

уже пробовал, безрезультатно – bazookyelmo

0
import java.util.Scanner; 
import java.util.Stack; 


public class test5 { 

private int numRows; 
private int numCols; 

public test5(){ 
Scanner input = new Scanner(System.in); 
System.out.println("Enter number of rows: "); 
numRows = input.nextInt(); 
System.out.println("Enter number of cols: "); 
numCols = input.nextInt(); 

Stack<Point>stack = new Stack<Point>(); 
stack.push(new Point(0,0)); 


while(!stack.isEmpty()){ 

    if(currentPath(stack.pop(),stack)){ 
     System.out.println("Maze is solvable"); 
    } 



} 

} 

public static void main(String[]args){ 

    new test5(); 

} 

private boolean currentPath(Point point, Stack<Point>stack){ 
    int currentRow = point.getRow(); 
    int currentCol = point.getCol(); 

    while(currentRow!=numRows-1 || currentCol!=numCols-1){ 
     boolean canGoRight = canGoRight(currentRow,currentCol); 
     boolean canGoUp = canGoUp(currentRow,currentCol); 
     boolean canGoDown = canGoDown(currentRow,currentCol); 

     if(canGoRight){ 
      if(canGoUp){ 
       stack.push(new Point(currentRow-1,currentCol)); 
      } 
      if(canGoDown){ 
       stack.push(new Point(currentRow+1,currentCol)); 
      } 
      currentCol = currentCol+1; 
     } 
     else{ 
      if(canGoUp){ 
       if(canGoDown){ 
        stack.push(new Point(currentRow+1,currentCol)); 

       } 
       currentRow = currentRow-1; 

      } 
      else if(canGoDown){ 
       currentRow = currentRow+1; 
      } 
      else{ 
       return false; 
      } 

     } 
    } 

    return true; 
} 



private boolean canGoUp(int row, int col){ 
    return row-1>=0; 
} 

private boolean canGoRight(int row, int col){ 
    return col+1<numCols; 
} 

private boolean canGoDown(int row, int col){ 
    return row+1<numRows; 
} 

class Point{ 
    private int row; 
    private int col; 

    public Point(int row, int col){ 
     this.row = row; 
     this.col = col; 
    } 

    public int getRow(){ 
     return row; 
    } 

    public int getCol(){ 
     return col; 
    } 
} 
} 
+0

может быть глупым вопросом ... но где мой файл лабиринта? – bazookyelmo

+0

Если вы используете eclipse, вы можете поместить его в папку проекта. – Solace

Смежные вопросы