【问题标题】:Array index out of bounds error in 2d array during linear search [closed]线性搜索期间二维数组中的数组索引越界错误[关闭]
【发布时间】:2013-03-15 01:35:10
【问题描述】:

我正在编写一个程序,该程序的作用类似于检票器。它显示可能的座位选择图表及其价格,并询问用户是否希望按数量或价格选择座位。它的工作原理就像它假设的按号码在座位上一样,但是当我尝试按价格找到座位时,我得到一个数组索引超出范围错误。我很困惑,因为它假设从零开始线性搜索。我不明白为什么会出现这个错误。

import java.util.Scanner;

public class FindTicket{
  public static void main(String[] args){
    String answer="number";
    Scanner kb=new Scanner(System.in);
    int[][] seats= {
      {10,10,10,10,10,10,10,10,10,10},
      {10,10,10,10,10,10,10,10,10,10},
      {10,10,10,10,10,10,10,10,10,10}, 
      {10,10,20,20,20,20,20,20,10,10}, 
      {10,10,20,20,20,20,20,20,10,10}, 
      {10,10,20,20,20,20,20,20,10,10}, 
      {20,20,30,40,40,40,30,30,20,20}, 
      {20,30,30,40,50,50,40,30,30,20},
      {30,40,50,50,50,50,50,50,40,30}
    };

    printChart(seats);
    do{
      System.out.println("Would you like to choose a seat by number, price, or quit?");
      answer = kb.nextLine();
      if(answer.equals("price")){
        sellSeatbyPrice(seats);}
      if(answer.equals("number")){ 
        sellSeatbyNumber(seats);}
      printChart(seats);
    }while(!answer.equals("quit"));
  }

  public static void printChart(int[][] seats){
    for (int i=0; i<seats.length; i++)
    {
      for(int j=0; j<seats[0].length; j++)
      {
        System.out.printf("%8d", seats[i][j]);
      }
      System.out.println();
    }
  }

  public static int[][] sellSeatbyPrice(int[][] seats){
    Scanner kb=new Scanner(System.in);
    int ticketprice;
    int row = 0, col = 0;
    boolean found = false, seatavaliable=true;
    do{
      System.out.println("What is your prefered ticket price?");
      ticketprice=kb.nextInt();
      while (row<seats.length && !found){
        do{
          if(seats[row][col] == ticketprice){
            found = true;}
          else{
            col++; }  
        }while(col<seats[0].length &&!found);
        if(seats[row][col] == ticketprice){
          found = true;}
        else{
          row++;} 
      }
      if(found){
        seats[row][col] = 0; }
      else {
        System.out.println("Seat not found at specified price.");
        seatavaliable=false;}
    }while(seatavaliable==false);

    return seats;
  }

  public static int[][] sellSeatbyNumber(int[][] seats){
    Scanner kb=new Scanner(System.in);
    int row = 0, col = 0;
    int editedrow, editedcol;
    boolean seatavaliable = true;
    do{
      System.out.println("What is your prefered seat number?  Please enter row then column.");
      row=kb.nextInt();
      col=kb.nextInt();
      editedrow = 9-row;
      editedcol = col - 1;
      if(seats[editedrow][editedcol] > 0){
        seats[editedrow][editedcol] = 0;}
      else{
        System.out.println("Seat is not avaliable.");
        seatavaliable=false;}
    }while(seatavaliable==false);

    return seats;
  }

}

【问题讨论】:

  • 您在哪一行出现越界错误?
  • 要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与您期望发生的情况进行比较。一旦两者发生分歧,你就发现了你的问题。 (然后如果有必要,你应该构造一个minimal test-case。)
  • @Michael 它说我在 27 和 61 有错误。
  • @Oil Charlesworth 对于我的课程,我们必须使用 JGrasp,而且我们还没有学习过调试器。我可以在网上找到这些信息吗?

标签: java multidimensional-array linear-search


【解决方案1】:

因为do...while

当这段代码完成后,col 将大于你的数组的长度。

看看cmets:

public static int[][] sellSeatbyPrice(int[][] seats){
    Scanner kb=new Scanner(System.in);
    int ticketprice;
    int row = 0, col = 0;
    boolean found = false, seatavaliable=true;
    do{
      System.out.println("What is your prefered ticket price?");
      ticketprice=kb.nextInt();
      while (row<seats.length && !found){
        do{
          if(seats[row][col] == ticketprice){
            found = true;}
          else{
            col++; }  // this line, in the last iteration, will make col=seats[0].length
        }while(col<seats[0].length &&!found);
        if(seats[row][col] == ticketprice){ //col with value greater than it should.
          found = true;}
        else{
          row++;} 
      }
      if(found){
        seats[row][col] = 0; }
      else {
        System.out.println("Seat not found at specified price.");
        seatavaliable=false;}
    }while(seatavaliable==false);

    return seats;
  }

【讨论】:

  • 我没有使用seats.length 和seats[0].length,而是创建了常量来代替,目的是让最终迭代产生col
  • 如果更新 col 的值,然后发现它大于最大值并再次使用 col 的值,它将超出范围。不管是使用数组长度还是常量。
  • 我将内部 do..while 更改为一段时间,并在第一行之后添加了一行,同时说 'col=0;'这似乎解决了这个问题。感谢您的帮助!
【解决方案2】:

nextInt() 方法离开\n(结束行)符号并立即被nextLine() 拾取,跳过下一个输入。您要做的就是对所有内容都使用nextLine(),然后再对其进行解析:

String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int

这是迄今为止最简单的避免问题的方法——不要混用你的“下一个”方法。仅使用 nextLine(),然后解析 ints 或单独的单词。


您不能关闭另一个Scanner,因为它会关闭底层InputStream,因此第一个Scanner 不能再从同一个InputStream 中读取,您会得到一个NoSuchElementException


最后一点:您应该在完成后关闭Scanner 以节省系统资源。

【讨论】:

  • 如何关闭扫描仪?
  • 对于您的代码,kb.close(),当您完成使用 1 Scanner
猜你喜欢
  • 2014-03-04
  • 2013-05-01
  • 2014-06-19
  • 2014-01-03
  • 2013-12-09
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
相关资源
最近更新 更多