为什么我会变空?

时间:2014-04-03 01:47:57

标签: java methods null

所以我有单独的课程,我正在学习如何用方法将它们相互融合。寻找一个解释为什么我为某些方法得到null,我已经坚持了几个小时。

主要“百吉饼”课程:

  public class Bagels {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Player first = new Player();
    Engine second = new Engine();

    System.out.println("Welcome!");

    second.getNumDigits();
    first.getName();

    System.out.println("Starting game #" +first.gamesCompleted );
    System.out.println("" );


    first.askForGuess();

    second.setGuessConvert(first);

    second.convertNumtoDigitArray(second.guessConvert);

    second.generateNewSecret();


    System.out.println("" + second.userGuessArray.length); //NULL error when run
    System.out.println("" + second.secretNumber.length); //NULL error when run

    Validator.validateGuess(second.secretNumber, second.userGuessArray, second.numDigits);

引擎类:

    import java.util.Random;
   import java.util.Scanner;
    public class Engine {

public int numDigits, numDigitsSet;
public int i;
public int[] secretNumber, userGuessArray;
public Random randomNumberGenerator;
public String guessConvert;

Scanner sc = new Scanner(System.in);

public void setNumDigits()
{

    numDigitsSet = numDigits;

}

public void setGuessConvert(Player player)
{
    guessConvert = player.userGuess;
}

public int getNumDigits()
{
    System.out.print("Enter the number of digits to use: ");
    return numDigits = sc.nextInt();

}

public void generateNewSecret() //NULL
{
Random rand = new Random();{
for (int i=0; i<numDigitsSet; i++)
{
    secretNumber[i]= rand.nextInt(10);

        }
    }
}

public int[] getSecretNumber()
{
     for (int j=0; j<secretNumber.length; j++) //NULL
     {
         System.out.println("" + secretNumber[j]);
     }
    return secretNumber;
}

public void convertNumtoDigitArray(String guessConvert) //NULL
{
    String[] userGuessSplit = guessConvert.split(",");
    int[] userGuessArray = new int[userGuessSplit.length];
    for (int j=0; j<userGuessSplit.length; j++)
    {
        userGuessArray[j] = Integer.parseInt(userGuessSplit[j]);
    }
}

}   

1 个答案:

答案 0 :(得分:0)

在Engine类的generateNewSecret函数中,您必须在使用

之前初始化secretNumber
    public void generateNewSecret()
    {
    Random rand = new Random();{
secretNumber =  new int[numDigitsSet];
    for (int i=0; i<numDigitsSet; i++)
    {
        secretNumber[i]= rand.nextInt(10);

            }
        }
    }

在convertNumtoDigitArray函数中,我认为你应该检查一下guessConvert,可能里面没有逗号。

public void convertNumtoDigitArray(String guessConvert)
{
    String[] userGuessSplit = guessConvert.split(",");
    int[] userGuessArray = new int[userGuessSplit.length];
    for (int j=0; j<userGuessSplit.length; j++)
    {
        userGuessArray[j] = Integer.parseInt(userGuessSplit[j]);
    }
}