0

I'm trying to take a String that is a number and convert it into an int array. The value for the string is created in the generateNewSecret() method and I'm trying to get this value converted into an int array and then store it in the instance secretNumber. The instance numDigits value is taken from another class and is used in here. The method convertNumToDigitArray is what I'm using to do this but I can't get this to work. I keep getting this error message:

java.lang.StringIndexOutOfBoundsException

Any help is appreciated.

import java.util.Random;

public class Engine
{
private int numDigits;
private int[] secretNumber = new int[numDigits];
private Random randomNumberGenerator = new Random();


public int[] convertNumToDigitArray(String number)
{
    int numDigits = number.length();
    int[] convertNumToDigitArray = new int[numDigits];
    for(int i = 0; i <= numDigits; i++)
    {
        convertNumToDigitArray[i] =  number.charAt(i);
    }
    return convertNumToDigitArray;
}

public int getNumDigits()
{
    return numDigits;
}

public int[] getSecretNumber()
{
    return this.secretNumber;
}

//creates a random number with a certain length that matches numDigits, 
 // stores in a string value
//Ex. numDigits = 3; secret = 647;
public void generateNewSecret()
{
    int secret = 0;
    for(int i = 0;i <= numDigits; i++)
    {

    secret = secret * 10 + randomNumberGenerator.nextInt(9);

    }
    secret = secret/10;
    String secretNum = Integer.toString(secret);

    setSecretNumber(convertNumToDigitArray(secretNum));


}


public void setNumDigits(int numDigits)
{
    this.numDigits = numDigits;
    secretNumber = new int[numDigits];
}

public void setSecretNumber(int[] secretNumber)
{

    this.secretNumber = secretNumber;
}
}
toha
  • 4,097
  • 3
  • 31
  • 49
C prof
  • 3
  • 3

1 Answers1

0

You can achieve it this way:

int[] numArray = new int[numDigits];
for (int i = 0; i < number.length(); i++)
{
  numArray[i] = number.charAt(i) - '0';
}
Bhagwati Malav
  • 2,599
  • 1
  • 16
  • 31