有一个任务:如果双字输入String接收到“”或“”,则打印null null。
我以这种方式解决了这个问题:
if (fullText == "" || fullText == " ") {
firstWord = null
lastWord = null
} else if (firstWord == "" || firstWord == " ") {
firstWord = null
} else if (lastWord == "" || lastWord == " ") {
lastWord = null
}
问题:如果不求助于如此庞大的结构,是否可以做不同的事情?
当然可以,你有几个 if-s 只是无缘无故的。因为如果第一个词和第二个词都是gap,那么一般的词就变成gap了,可以这样写(不看语法,因为没查,查逻辑)
通常,这些检查可以用 .isBlank() 代替,因为此方法检查字符串是否为空或由空格组成