【问题标题】:Java Scanner loop?Java扫描程序循环?
【发布时间】:2011-07-01 16:55:21
【问题描述】:

我正在制作一个迷宫求解器。出于某种原因,每次到达标有“-->”的行时,都会输出“输入高度:”。就像那条线(到达时不运行)以某种方式使方法循环。

private void makeMap() {
    Map map; //used to convert the char array into a graph
    int height; //the height of the map by user input
    char[][] array; //used to store the char map

    System.err.println("Enter height: ");
    height = scanner.nextInt(); //gets and stores the height from the user

    array = new char[height][]; //initializes the map with input height
    for(int i=0; i<height; i++) { //adds row by row to the map array
        System.err.print("Enter next line of map: ");
        array[i] = scanner.next().toCharArray();
    }

    --> map = new Map(array); //initializes the map by passing the char array

    graph = map.makeGraph(); //creates a graph from the char array
  }

我认为我的问题出在哪里,我用“-->”标记。我在标记行之前放置的任何代码都将执行,但是一旦到达该行,它就会循环回到该方法的顶部。下面是 Map 构造函数:

public Map(char[][] passMap) {
    adjList = new Vertex[map.length*map[0].length];
    map = passMap; //stores the passed map
}

有帮助总比没有帮助好。我已经在这几个小时了。谢谢。

【问题讨论】:

  • Scanner 类有一个“错误”。您可以尝试在nextIntnextFloat 之后执行next。有关更多信息,请参阅此主题和 RD1 的评论:stackoverflow.com/questions/4708219/…
  • 在构造函数中你有一个变量映射。这是类的私有字段吗?
  • “循环回到方法的顶部”是什么意思?
  • 在输出中使用System.err.println 是否有特殊原因?
  • 从您发布的内容来看,除非或直到从循环中调用 makeMap,否则代码不可能循环回“输入高度”行。因此,如果您查看部分内容会更好在哪里调用 makeMap 或为我们提供更全面的 sn-p 供我们研究。

标签: java loops java.util.scanner


【解决方案1】:

您的地图变量可能未初始化。变化:

adjList = new Vertex[map.length*map[0].length];

收件人:

adjList = new Vertex[passMap.length*passMap[0].length];

我还将您的 System.err.println() 呼叫更改为 System.out.println()。第一个用于错误输出,第二个用于正常控制台输出。

【讨论】:

  • 哇,非常感谢!我所要做的就是切换我的两个实例变量!我已经在这个地方待了几个小时了。你是个炸弹!! (感谢 .err 提示)!
【解决方案2】:

为什么不学习使用调试器(这很容易)并在该行设置一个断点。这会让你很快得到答案。

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    相关资源
    最近更新 更多