0

私は現在プログラムに取り組んでおり、Products[1] を呼び出すたびに null ポインター エラーは発生しませんが、Products[0] または Products[2] を呼び出すと null ポインター エラーが発生します。ただし、配列に [0] と 1 または 1 と 2 があるように、まだ 2 つの異なる出力が得られます。これが私のコードです

    FileReader file = new FileReader(location);
    BufferedReader reader = new BufferedReader(file);

    int numberOfLines = readLines();
    String [] data = new String[numberOfLines];
    Products = new Product[numberOfLines];
    calc = new Calculator();

    int prod_count = 0;
    for(int i = 0; i < numberOfLines; i++)
    {
        data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
        if(data[i].contains("input"))
        {
            continue;
        }
        Products[prod_count] = new Product();
        Products[prod_count].setName(data[1]);
        System.out.println(Products[prod_count].getName());
        BigDecimal price = new BigDecimal(data[2]);
        Products[prod_count].setPrice(price);


        for(String dataSt : data)
        {

            if(dataSt.toLowerCase().contains("imported"))
        {
                Products[prod_count].setImported(true);
        }
            else{
                Products[prod_count].setImported(false);
            }

        }



        calc.calculateTax(Products[prod_count]);    
        calc.calculateItemTotal(Products[prod_count]);
        prod_count++;

これは出力です:

imported box of chocolates
1.50
11.50
imported bottle of perfume
7.12
54.62

このプリントは機能しますSystem.out.println(Products[1].getProductTotal());

これはヌルポインタになりますSystem.out.println(Products[2].getProductTotal());

これもヌルポインタになるSystem.out.println(Products[0].getProductTotal());

4

3 に答える 3

0

ライン番号と新しい製品オブジェクトには異なるインデックスを使用する必要があります。20 行あり、そのうちの 5 行が「入力」の場合、新しい製品オブジェクトは 15 個しかありません。

例えば:

int prod_count = 0;

for (int i = 0; i < numberOfLines; i++)
{
        data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
        if (data[i].contains("input"))
        {
            continue;
        }
        Products[prod_count] = new Product();
        Products[prod_count].setName(data[1]);
        // etc.
        prod_count++; // last thing to do
}
于 2013-09-22T00:30:12.493 に答える