Cham
Cham

Reputation: 131

String to Character Array

I have a problem with my code below:

public class stringToChar {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    char[] sCharArr;
    String[] odd = new String[n];
    String[] even = new String[n];
    for(int i = 0; i < n; i++) {
        sCharArr = in.next().toCharArray();
        for(int j = 0; j < sCharArr.length; j++) {
            if(j % 2 == 0)
                even[i] += sCharArr[j];
            else
                odd[i] += sCharArr[j];
        }
   }
   for(int i = 0; i < n; i++) {
       System.out.println(even[i] + "  " + odd[i]);
   }
 }
}

My issue is on the output it has a Null in the result. Here is a sample scenario:

2
John
Cena

Answer should be:

Jh  on
Cn  ea

But my code answer is:

NullJh  Nullon
NullCn  Nullea

Upvotes: 1

Views: 45

Answers (1)

GhostCat
GhostCat

Reputation: 140613

Your problem is that the new arrays are initialized with all null Strings. Then your code is not assigning values to all array elements, but just to some of them!

Finally you print your array, and surprise, those values that were null and that have not been changed - are still null (and when you print a null string ... it prints "null" [ yes, null, not Null; you got a little mistake there in your output example ]

You see, you iterate from 0 to the length of your two arrays. And if the number is even, you put a value in the even[i]; and if the value is odd, it goes to odd[i]. Lets take even - in that case, odd[i] simply stays null!

One way to fix that:

List<String> even = new ArrayList<>();
List<String> odd = new ArrayList<>();

And now, instead of setting a certain index in even/odd; you simply do:

even.add(some new value);

and to add those single characters:

even.add(new String(sCharArr));

Doing so, even and odd will (in the end) contain exactly the values that you added to each list; but no "residual" nulls. For the record: the way how you split up strings, to then pull them back into a String array isn't exactly the most simple/straight forward way to solve the problem.

But I leave "further" simplifications" as exercise to the user.

Upvotes: 1

Related Questions