"Nulo" se imprime cuando trato de imprimir el valor de la matriz en java programa

Habiballah Hezarehee:

Mi problema es que cuando quiero imprimir cualquier elemento de mi matriz 2D del nulo aparece en lugar del valor del elemento de la matriz. ¿En qué puedo resolver el problema? y por lo que obtener este resultado a pesar de mi matriz tiene miembros? (Soy nuevo en la programación)

Traté simplemente imprimir una miembro de la matriz escribiendo el número de elemento directamente pero aún así, hay algún problema por lo que los números aleatorios no son el problema. También he tratado de definir una nueva matriz dentro del método pickCard () con el fin de copiar la matriz cardList a ella pero no ayuda tampoco.

Tengo 2 clases diferentes, la primera clase se llama Tutorial e incluye el main () método y el otro se llama Kortlek y todos mis códigos están ahí.

Esta es la clase Tutorial

package tutorial;

import java.util.Arrays;
import java.util.Scanner;

public class Tutorial {
    public static void main(String[] args) {

        // Using Scanner class to get in the input from user
        Scanner input = new Scanner(System.in);

        // We initialize our class Kortlek
        Kortlek newKortlek = new Kortlek();

        // Here we choose a nickname for user: 
        System.out.print("Please choose a name: ");
        String Username = input.next();
        String pcName = newKortlek.nickNamePC();


        String userAnswer;
        int userScore = 1;
        int pcScore = 2;
        do {
            System.out.println("You picked up: " + newKortlek.pickCard());
            System.out.println(pcName + " has picked up: "  + newKortlek.pickCard());
            System.out.println("Do you want to continue? write yes or no");
            userAnswer = input.next();

        } while (!userAnswer.equals("no"));
       System.out.println("Your score is: " + userScore);
       System.out.println(pcName + "'s score is: " + pcScore);
    }
}

Esta es la clase Kortlek

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tutorial;

import java.util.Random;

/**
 *
 * @author hezarehee
 */
public class Kortlek {

    Random r = new Random();
    /**
     * In this method we create 2D array in order to group each card color and its cards (1-13)
     */
    String cardList[][] = new String[3][12];

    public String[][] buildCardGame () {
        String[] farg = {"Spader", "Hjarter", "Ruter", "Klover"};
        String[] nummer = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "Ace"};


        for (int i=0; i < farg.length; i++) {
            for (int j=0; j < nummer.length; j++) {
                cardList[i][j] = farg[i] + " " + nummer[j];
            }

        }
        return cardList;
    }

    /**
     * Here we make a method that let computer to choose a name from given names in array
     */
    public String nickNamePC () {
        String[] nickName = {"Daivd", "Rahim", "Michael", "Sara", "Marie", "Jenny"};

        int low = 0; 
        int high = 5; 
        int result =  r.nextInt(high-low) + low;
        String chosenName = nickName[result];
        return chosenName;
    }

    /**
     * Here we each time pick up a card from our 2D Array cardList[][] 
     */
    public String pickCard() {
        int takeColor = r.nextInt(3-1) + 1;
        int takeNumber = r.nextInt(12-1) + 1;

        // we put our random numbers into the array carDList
        String pickedCard = cardList[takeColor][takeNumber];
        return pickedCard;
    }

}

Necesito hacer un juego de cartas (Rank y colores), en este juego los usuarios jugar contra el programa, primero en el cardList matriz, intenté crear 52 cartas diferentes para en 4 grupos (tréboles, diamantes, corazones, picas). Hice el método de matriz dentro llamado buildCardGame ().

Por el método pickCard (), trato de recoger una carta al azar mediante la adición de 2 números al azar de 0-3 para el color y 0-12 para el rango. Pero cuando lo imprimo a cabo por lo que obtener nula.

madplay:

En primer lugar, es necesario modificar en donde cardlistse inicializa.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tutorial;

import java.util.Random;

/**
 *
 * @author hezarehee
 */
public class Kortlek {

    Random r = new Random();
    /**
     * In this method we create 2D array in order to group each card color and its cards (1-13)
     */
    String cardList[][] = new String[4][13];

    // ArrayIndexOutOfBoundsException
    // String cardList[][] = new String[3][12];

    public String[][] buildCardGame () {
        String[] farg = {"Spader", "Hjarter", "Ruter", "Klover"};
        String[] nummer = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "Ace"};


        for (int i=0; i < farg.length; i++) {
            for (int j=0; j < nummer.length; j++) {
                cardList[i][j] = farg[i] + " " + nummer[j];
            }

        }
        return cardList;
    }

    /**
     * Here we make a method that let computer to choose a name from given names in array
     */
    public String nickNamePC () {
        String[] nickName = {"Daivd", "Rahim", "Michael", "Sara", "Marie", "Jenny"};

        int low = 0;
        int high = 5;
        int result =  r.nextInt(high-low) + low;
        String chosenName = nickName[result];
        return chosenName;
    }

    /**
     * Here we each time pick up a card from our 2D Array cardList[][] 
     */
    public String pickCard() {
        int takeColor = r.nextInt(3-1) + 1;
        int takeNumber = r.nextInt(12-1) + 1;

        // we put our random numbers into the array carDList
        String pickedCard = cardList[takeColor][takeNumber];
        return pickedCard;
    }

}


En segundo lugar, buildCardGameel método debe ser llamado

package tutorial;

// import java.util.Arrays; // not used
import java.util.Scanner;

public class Tutorial {
    public static void main(String[] args) {

        // Using Scanner class to get in the input from user
        Scanner input = new Scanner(System.in);

        // We initialize our class Kortlek
        Kortlek newKortlek = new Kortlek();

        // initialize the members
        newKortlek.buildCardGame(); 

        // Here we choose a nickname for user:
        System.out.print("Please choose a name: ");
        String Username = input.next();
        String pcName = newKortlek.nickNamePC();


        String userAnswer;
        int userScore = 1;
        int pcScore = 2;
        do {
            System.out.println("You picked up: " + newKortlek.pickCard());
            System.out.println(pcName + " has picked up: "  + newKortlek.pickCard());
            System.out.println("Do you want to continue? write yes or no");
            userAnswer = input.next();

        } while (!userAnswer.equals("no"));
        System.out.println("Your score is: " + userScore);
        System.out.println(pcName + "'s score is: " + pcScore);
    }
}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=238706&siteId=1
Recomendado
Clasificación