【发布时间】:2018-01-03 13:56:36
【问题描述】:
嗨,我有这段代码可以获取字符串中最短的单词:-
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = null;
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=1;i<words.length;i++){
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
int p = shortestLocation;
return p;
}
}
返回变量shortestLocation不能转换为int的错误:-
java:6: error: incompatible types: <null> cannot be converted to int
int shortestLocation = null;
我的问题是如何访问变量的范围,就像在这种情况下我知道出了什么问题。变量最短位置是在 if 语句的范围之外定义的,因此它只考虑初始化它的值。
如何使初始值更改为 if 语句值。这是一个范围问题,请帮助我是初学者。
【问题讨论】:
-
错误信息告诉你到底出了什么问题。不,这与范围无关。
-
您不能将 null 分配给原始类型 int。这与范围无关
-
我修复了它并将值更改为 0,但现在它一直返回 0。我的变量值永远不会更改为 if 语句后返回的值。
-
如果您的最短长度从 0 开始,您将如何找到字符数少于此的单词? “这个词的长度是否小于0?” - 不,它永远不会,所以变量永远不会改变,所以它总是 0。你的起始最短长度应该是第一个单词的长度。
-
为什么要初始化p?只返回最短位置。 #off 主题