我在以下代码中收到Local variable 'answerArray' is redundant
警告:
int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};
return answerArray;
完整方法:
public int[] answerArray (int answer) {
Random randomGenerator = new Random();
int fakeFirstAnswer = randomGenerator.nextInt(10);
int fakeSecondAnswer = randomGenerator.nextInt(10);
int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};
return answerArray;
}
我尝试过像下面这样的重构,但后来发现expects ;
错误。
return int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};
有人可以推荐一种语法吗?我刚刚开始使用Java / Android。
答案 0 :(得分:0)
在Java中,array variable declarations,
int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};
是
的简写int[] answerArray = new int[] {answer, fakeFirstAnswer, fakeSecondAnswer};
// ^-- the Java compiler does this
但是,return
不是变量声明,需要明确的new int[]
语法,如Sotirios指出
return new int[] {answer, fakeFirstAnswer, fakeSecondAnswer};
(在这两种情况下,Java都会自动确定数组的长度。)