gpt4 book ai didi

java - 使用 .split() 时为 null

转载 作者:行者123 更新时间:2023-12-01 23:01:22 33 4
gpt4 key购买 nike

嘿伙计们,我对java很陌生,我想知道是否有人可以解释为什么我在数组的开头得到一个随机空值,它是[null,r,b,o,e,r, t] 不知道为什么这样做!任何摆脱它的帮助都会很棒!

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;
}

提前致谢!

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

最佳答案

因为在第一个字符之前有一个空字符串。说 $ 是空字符串,那么你的字符串实际上是:

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

所以输出是:

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

基本上,在 split 中使用空字符串作为正则表达式并不是一个好主意。您可以使用此正则表达式分割字符串字符:

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

输出是:

[a, b, c, d]

关于java - 使用 .split() 时为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23333328/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com