Java数组索引问题

标签 java arrays nullpointerexception

cantmano是索引,从0开始。另一种方法是用cant++递增。 我重新检查 0 <= cantmano <= 10

public void dibujar(){
    //actualiza la pantalla
    if (cantmano >= 0 && cantmano < 10 && cantcroupier >= 0 && cantcroupier < 10){
        TextView textomano = (TextView)findViewById(R.id.textView3);
        TextView textocroupier = (TextView)findViewById(R.id.textView5);
        CharSequence buffer = textomano.getText();

        textomano.setText( buffer + " " +
            String.valueOf(manojugador[cantmano].getPalo())+ " de " +
            String.valueOf(manojugador[cantmano].getNumero()) ); // <-- ERROR

        textocroupier.setText( String.valueOf(cantmano) );
    }
}

我得到了一个很好的

Caused by: java.lang.NullPointerException
    at com.pruebas.blackjack.blackjack.dibujar(blackjack.java:58)
    at com.pruebas.blackjack.blackjack.onCreate(blackjack.java:23)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2717)

EDITS: .getNumero() returns the int with the value of a requested CARD. (playing card type) .getPalo() returns an int where 1= diamonds, etc.

initialization of manojugador:

Carta manojugador[]= new Carta[10];

constructor of Carta:

public Carta(){
    int palo=0;
    int numero=0;
}

午夜更新: 通过一些改进,我设法克服了错误。但是现在数组在写入时全为 0 值。这一定很容易解决,但这是接受最佳答案之前的最后一步。

添加卡片的方法如下:

public void hit(View v){
        //sacan cartas
        if (cantmano < manojugador.length){
        manojugador[cantmano]=mazo.darcarta(); //adds a random Card to the manojugador. mazo means deck.
        manocroupier[cantcroupier]=mazo.darcarta(); //adds a random Card to the manojugador. mazo means deck.
        cantmano++;
        cantcroupier++;
        }
        dibujar();
    }

最佳答案

您必须初始化数组它的元素。如果你只是有这个:

Carta manojugador[]= new Carta[10];

那么数组的所有 10 个元素都将为 null。您还必须初始化每个元素。像这样:

for(int i=0, length=manojugador.length; i<length; i++) {
    manojugador[i] = new Carta();
}

更新:

我看到在您的 hit() 方法中,我看到您有:

if (cantmano <= 8) {

不应该是:

if (cantmano < 10) {

或者更好:

if (cantmano < manojugador.length) {

我认为您的代码中发生的导致 NullPointerException 的事情是 manojugador[9] 永远无法初始化。

关于Java数组索引问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6515587/

相关文章:

java - Pattern.compile 没有标志?

java - 什么是NullPointerException,我该如何解决?

java - 数组的空指针异常

android - Android Studio 中的方法调用突出显示错误

java - 存储在线程安全集合中的对象线程安全吗?

Java 序列化问题 (java.io.StreamCorruptedException)

c++ - 在现代 C++ 中优雅地定义多维数组

c、从头开始shrink分配的空间

javascript - 将对象数组转换为二维数组

java - 企业应用程序项目和 EJB 项目有什么区别?