Question

hey guys i'm very new to java, and i was wondering if someone could explain why i'm getting a random null at the beginning of my array it goes [null,r,b,o,e,r,t] not sure why it does that! any help getting rid of it would be awesome!

public static String [] Wordarray(Scanner input)
   {
      String [] temp = {};
      String word = "";
      do{
         System.out.println("Enter a word you'd like to be guess");
         word = input.nextLine().toLowerCase();
         if(word.length()<5)
            System.out.println("Error....");
      }while(word.length()<5);
      String [] words = word.split("");

      return words;
}

Thanks in advance!

example input to output Enter a word you'd like to be guess
beees

The word contains 6letters.
Amount of chances left 7

avaliable letters : [, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
Enter a letter : 
b
[]
[-, b, -, -, -, -]
[null, b, null, null, null, null]
Amount of chances left 7

avaliable letters : [, a, , c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
Enter a letter : 
e
[-, b, -, -, -, -]
[-, -, e, e, e, -]
[null, b, e, e, e, null]
Amount of chances left 7

Enter a letter : 
s
[-, -, e, e, e, -]
[-, -, -, -, -, s]
[null, b, e, e, e, s]
Amount of chances left 6
Was it helpful?

Solution

because before first character there is an Empty String. say $ is Empty String, then your String actually is :

rboert -> $r$b$o$e$r$t

so the output is :

[null,r,b,o,e,r,t] 

basically it is not a good idea to use empty string as regex in split. you could split string character using this regex:

"abcd".split("(?<=.)");

and output is :

[a, b, c, d]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top