我的Java程序find path不输出任何内容

我的Java程序find path不输出任何内容,java,Java,我写了一个递归程序来打印点之间的路径,但不打印任何东西 public static void find(int a, int b, int [][] myArray) { System.out.print("thisWay " + a + " "); if (myArray[a][b] != 0) { int point = myArray[a][b]; find(a, point, my

我写了一个递归程序来打印点之间的路径,但不打印任何东西

public static void find(int a, int b, int [][] myArray) 
    {
        System.out.print("thisWay " + a + " ");
        if (myArray[a][b] != 0) 
        {
            int point = myArray[a][b];
            find(a, point, myArray);
            System.out.print("thisWay " + point + " ");
            find(point, b, myArray);
        }
        System.out.print("thisWay " + b + " ");
    }
这是我的主要观点

public static void main(String[] args) 
    {   
        int[][] myArray = new int[][]
        {
           {7, 0, 0, 8, 7, 8, 3, 0, 7},
           {7, 0, 7, 0, 7, 8, 0, 2, 7},
           {0, 4, 5, 1, 1, 8, 0, 1, 5},
        };
        find(2, 4, myArray);
    }

当我运行代码时,会得到一个
java.lang.StackOverflowerError
,但它至少会打印出值,直到出现错误为止。System.out可能正在系统上缓冲。每次打印后,通过调用
System.out.Flush()
刷新它。

您需要检查此点是否超出数组边界,然后检查此点是否不等于零。 大概是这样的:

public class Main  {
      static int x=0;
public static void find(int a, int b, int [][] myArray) throws InterruptedException 
{
    System.out.println("thisWay " + a + " ");
    if (myArray.length>a&&(myArray[0].length>b&&myArray[1].length>b&&myArray[2].length>b)&&myArray[a][b] != 0&&x<100) 
    {
            x++;
        int point = myArray[a][b];
        find(a, point, myArray);
        System.out.print("thisWay " + point + " ");
        find(point, b, myArray);
    }else{
    System.out.print("thisWay " + b + " ");
    }
}
public static void main(String[] args) throws InterruptedException 
{   
    int[][] myArray = new int[][]
    {
       {7, 0, 0, 8, 7, 8, 3, 0, 7},
       {7, 0, 7, 0, 7, 8, 0, 2, 7},
       {0, 4, 5, 1, 1, 8, 0, 1, 5},
    };
    System.out.println(myArray.length);
    find(1, 2, myArray);
}
}
公共类主{
静态int x=0;
公共静态void find(int a、int b、int[][]myArray)抛出InterruptedException
{
System.out.println(“thisWay”+a+”);

如果(myArray.length>a&&(myArray[0].length>b&&myArray[1].length>b&&myArray[2].length>b)&&myArray[a][b]!=0&&x则
stdout
的I/O通常是缓冲的,这会阻止立即显示输出(
stderr
不是),则
PrintStream
的实例通常也是行缓冲的


刷新缓冲区最简单的方法通常是打印
'\n'
(例如
System.out.print(“一些文本…\n”)
System.out.println(“一些文本…”)

尝试
System.out.println()
,而不是所有
System.out.print()
语句,这些语句应该将缓冲区刷新到控制台

除此之外,您还应注意两件事:

  • 数组边界检查

    如果a=2,b=5=>point=8,下一次调用时您将尝试myArray[8][5],它将给出ArrayIndexOutOfBoundsException

    Sol:将数组的边界作为参数发送给find方法,并检查a和b是否在该边界内

  • 递归级别检查

    您的程序可能会在该数组中无限期地循环搜索,所以您可能会在同一点上得到StackOverflow异常

    Sol:添加一个参数
    depth
    ,该参数指定在每次递归调用时要递归的“depth”程度,并将其递减,每次输入find()方法时,检查它是否为
    >0


Is不打印任何内容?根本没有输出?您第一次是如何调用
find(…)
的?您的主代码是什么?您何时调用此方法?ooops刚刚忘记添加我的主代码