0

I have been trying for hours to change a user inputted string of numbers into an integer, then create and print an integer array with those integers. I finally got it, but the first element of the printed array is always zero. I don't know how to fix it. I feel like it is really simple, but I am exhausted and am getting stuck on the easiest things. Does anyone know what is wrong? I'll put my code below.

String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];

for (int a : myArray) {
    System.out.print(a);
    System.out.print(" ");
    for (int i = 0; i < size; i++) {
        char n = stringNum.charAt(i);
        int intNum = Character.getNumericalValue(n);
        myArray[i] = intNum;
    }
}

// input: 12345 // output: 0 2 3 4 5

1 Answer 1

0

You have mixed up printing the array and populating the array.

First, parse the input string and populate the array

String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];

for (int i = 0; i < size; i++) {
    char n = stringNum.charAt(i);
    int intNum = Character.getNumericalValue(n);
    myArray[i] = intNum;
}

Then print the elements,

for (int a : myArray) {
    System.out.print(a);
    System.out.print(" ");
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.