繁体   English   中英

使用Java中的扫描程序类从文件中获取输入错误

[英]Error in taking input from file using scanner class in java

我想使用Java中的扫描器类从文件中获取输入。 我想从文件中读取不同城市的两个坐标,然后将它们存储在City对象类型的ArrayList中。

输入文件格式如下:

NAME : att48
COMMENT : 48 capitals of the US (Padberg/Rinaldi)
TYPE : TSP
DIMENSION : 5
EDGE_WEIGHT_TYPE : ATT
NODE_COORD_SECTION
1 6734 1453
2 2233 10
3 5530 1424
4 401 841
5 3082 1644

我的示例代码片段如下: TourManager是一个包含City对象的ArrayList的类。 我没有在这里显示。 城市类别包含城市的每个详细信息(x,y坐标)。

try 
    {
        Scanner in = new Scanner(new File("att48.tsp"));
        String line = "";
        int n;
        //three comment lines
        in.nextLine();
        in.nextLine();
        in.nextLine();
        //get n
        line = in.nextLine();
        line = line.substring(11).trim();
        n = Integer.parseInt(line);
                    City[] city= new City[n];
       for (int i = 0; i < n; i++) {
                    city[i].x=0;
                    city[i].y=0;
        }

        //two comment lines
        in.nextLine();
        in.nextLine();

        for (int i = 0; i < n; i++)
        {
            in.nextInt();
            city[i].x =  in.nextInt();
            city[i].y =  in.nextInt();
            TourManager.addCity(city[i]);
        }
    } 
    catch (Exception e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但是我在行中得到了NullPointerException

  city[i].x =  in.nextInt();

尽管我之前已将其初始化为0,但是代码抛出NullPointerException

为了清楚起见,城市等级如下:

public class City {
    int x;
    int y;

  // Constructs a city at chosen x, y location
  public City(int x, int y){
    this.x = x;
    this.y = y;
  }
}

代码中有问题吗?

您收到错误是因为这样做之后:

City[] city= new City[n];

您尚未为单个city[i]元素分配内存。

您必须执行类似的操作,但是为此您需要在城市类中添加默认构造函数,因为随后要分配x和y:

for (i=0;i <n ;i++){
   city[i]= new City();     
}

在您的City类中添加以下构造函数:

public City(){

}

或者我建议您修改您的City班级:

public class City {
    private int x;
    private int y;

    // Constructs a city at chosen x, y location
    public City(int x, int y) {
        this.setX(x);
        this.setY(y);
    }

    public City() {

    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM