从 .txt 填充数组时出现 NullPointerException

发布于 2025-01-04 13:38:30 字数 2236 浏览 2 评论 0原文

事情是这样的,我需要从 .txt 文件填充一个数组。我使用 Scanner 类来读取每一行,并从 Ints 中获取要存储在数组中的令牌的位置:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class Aplicacion {

    static Elemento _tablero[][] = new Elemento[8][8];


    public static Elemento[][] Leertxt() throws FileNotFoundException,IOException
    { 
        Scanner sc = new Scanner(new File("C:/Users/Owner/Documents/UNIMET/Trimestre  5/Estructura de Datos/Proyecto 1a/src/inicio.txt"));

        while(sc.hasNext())
        {
            String ln = sc.next();          

           if (ln.equals("Pared"))
        {
            int i = sc.nextInt();
            int j = sc.nextInt();

             _tablero[i][j] = new Pared(i,j);//crea una pared nueva
        } 
         else if (ln.equals("Fantasma"))    
          {
             int i = sc.nextInt();
             int j = sc.nextInt(); 

           _tablero[i][j] = new Fantasma(i,j);//crea un fantasma nuevo
      }
        else if (ln.equals("Vacio"))
        {
            int i = sc.nextInt();
            int j = sc.nextInt();

            _tablero[i][j] = new Vacio(i,j); //crea un vacio
        }


     }


       for(int i=0; i<_tablero.length;i++)
        {
          for(int j=0;j<_tablero.length;j++)
            {
               if (_tablero[i][j] instanceof Vacio)
               {
                 _tablero[i][j] = null; 

                 _tablero[i][j] = new Punto(i,j);
            }
        }
    }     return _tablero;
}  

public  void mostrar() throws FileNotFoundException, IOException
{   Elemento[][] tab = Leertxt(); 
    for (int i = 0; i < tab.length; i++)
  { for(int j = 0;j < tab.length; j++)
      {
           System.out.print("  "+ tab[i][j].mostrar();
          }
       System.out.println();//salto de linea
      }
}

它编译时没有错误,但是当我运行时,我最终得到了

Exception in thread "main" java.lang.NullPointerException
        at Aplicacion.mostrar(Aplicacion.java:73)
    at JuegoPacman.main(JuegoPacman.java:27)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)

我不明白它在哪里得到的第 73 行出现 NullPointerException。 mostrar 方法是 Elemento 类中的一个抽象方法,它只打印一个符号...任何帮助都会很乐意接受

here's the deal, i need to fill an array from a .txt file. I'v used the Scanner class to read each line and from the Ints get a position for the token to be stored in the array:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class Aplicacion {

    static Elemento _tablero[][] = new Elemento[8][8];


    public static Elemento[][] Leertxt() throws FileNotFoundException,IOException
    { 
        Scanner sc = new Scanner(new File("C:/Users/Owner/Documents/UNIMET/Trimestre  5/Estructura de Datos/Proyecto 1a/src/inicio.txt"));

        while(sc.hasNext())
        {
            String ln = sc.next();          

           if (ln.equals("Pared"))
        {
            int i = sc.nextInt();
            int j = sc.nextInt();

             _tablero[i][j] = new Pared(i,j);//crea una pared nueva
        } 
         else if (ln.equals("Fantasma"))    
          {
             int i = sc.nextInt();
             int j = sc.nextInt(); 

           _tablero[i][j] = new Fantasma(i,j);//crea un fantasma nuevo
      }
        else if (ln.equals("Vacio"))
        {
            int i = sc.nextInt();
            int j = sc.nextInt();

            _tablero[i][j] = new Vacio(i,j); //crea un vacio
        }


     }


       for(int i=0; i<_tablero.length;i++)
        {
          for(int j=0;j<_tablero.length;j++)
            {
               if (_tablero[i][j] instanceof Vacio)
               {
                 _tablero[i][j] = null; 

                 _tablero[i][j] = new Punto(i,j);
            }
        }
    }     return _tablero;
}  

public  void mostrar() throws FileNotFoundException, IOException
{   Elemento[][] tab = Leertxt(); 
    for (int i = 0; i < tab.length; i++)
  { for(int j = 0;j < tab.length; j++)
      {
           System.out.print("  "+ tab[i][j].mostrar();
          }
       System.out.println();//salto de linea
      }
}

It compiles with no error, but when I run I end up getting

Exception in thread "main" java.lang.NullPointerException
        at Aplicacion.mostrar(Aplicacion.java:73)
    at JuegoPacman.main(JuegoPacman.java:27)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)

I dont understand where is it getting the NullPointerException in line 73.
The mostrar method is an abstract method in the Elemento class and it just prints a symbol...any help would be happily accepted

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你如我软肋 2025-01-11 13:38:30

因为当您尝试调用 tab[i][j].mostrar() 时 ... tab[i][j]null 。您永远不会将对象放入数组中的该位置。

您的 Leertxt() 方法中没有任何内容可以确保所有 64 个位置都收到一个对象。

如果您想找出哪个位置,请将循环更改为:

Elemento[][] tab = Leertxt(); 
for (int i = 0; i < tab.length; i++)
{ 
    for(int j = 0;j < tab[i].length; j++)
    {
        if (tab[i][j] == null)
            System.out.println("null at location: [" + i + "," + j + "]");
        else
            System.out.print("  "+ tab[i][j].mostrar();
    }
    System.out.println();//salto de linea
}

Because when you attempt to call tab[i][j].mostrar() ... tab[i][j] is null. You never put an object in that location in the array.

There is nothing in your Leertxt() method that assures all 64 locations receive an object.

If you want to find out which location that is, change your loop to:

Elemento[][] tab = Leertxt(); 
for (int i = 0; i < tab.length; i++)
{ 
    for(int j = 0;j < tab[i].length; j++)
    {
        if (tab[i][j] == null)
            System.out.println("null at location: [" + i + "," + j + "]");
        else
            System.out.print("  "+ tab[i][j].mostrar();
    }
    System.out.println();//salto de linea
}
等待我真够勒 2025-01-11 13:38:30

进一步跟进 Brian Roach 的评论,我建议您添加到:

if (_tablero[i][j] instanceof Vacio)

将其扩展为包含空值(我假设在空白空间中,您还会包含空值):

if (_tablero[i][j] instanceof Vacio || _tablero[i][j] == null)

这样,如果文本文件中未定义某些内容,它将被定义这里。如果您愿意,您甚至可以在检测到空方块时抛出一个标志,以确保您找到空方块。

另一种选择是

System.out.print("  "+ tab[i][j].mostrar());

用 try/catch 块或三元运算包围:即问题第 73 行:

try{
    System.out.print("  "+ tab[i][j].mostrar());
} catch (NullPointerException ex){
    //haz algo
}

或者

System.out.print("  "+ ((tab[i][j] == null) ? "null" : tab[i][j].mostrar()));

Following up further on Brian Roach's comment, I suggest you add in to:

if (_tablero[i][j] instanceof Vacio)

To expand it to include nulls (I assume in empty space, you would also include null):

if (_tablero[i][j] instanceof Vacio || _tablero[i][j] == null)

So that if something is undefined in your text file, it will be defined here. If you want, you could even throw up a flag whenever it detects a null square to ensure that you track down the nulls.

The other option would be to surround:

System.out.print("  "+ tab[i][j].mostrar());

ie Problem line 73 with a try/catch block or a ternary operation:

try{
    System.out.print("  "+ tab[i][j].mostrar());
} catch (NullPointerException ex){
    //haz algo
}

Or

System.out.print("  "+ ((tab[i][j] == null) ? "null" : tab[i][j].mostrar()));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文