英文:
How do I append int in a int array(java)?
问题
第一个代码段没有问题:
public int[] maxEnd3(int[] nums) {
int max = Math.max(nums[0], nums[2]);
int[] result = {max, max, max};
return result;
}
然而,第二个代码段存在编译问题,我无法找出原因。请查看我的代码。谢谢!
public int[] maxEnd3(int[] nums) {
int first = nums[0];
int last = nums[2];
int[] result = new int[2];
if (first >= last) {
result = {first, first, first};
} else {
result = {last, last, last};
}
return result;
}
编译问题:
缺少 '}' 或非法的表达式开始。
英文:
I am working on an one of coding practice from codingbat which is
First one works with no problem,
public int[] maxEnd3(int[] nums) {
int max = Math.max(nums[0], nums[2]);
int[] result = {max, max, max};
return result;
}
however, second one have compile problems and I cannot figure out why. Please have a look at my code. Thanks!
public int[] maxEnd3(int[] nums) {
int first = nums[0];
int last = nums[2];
int[] result = new int[2];
if (first >= last) {
result = {first, first, first};
} else {
result = {last, last, last};
}
return result;
}
Compile problems:
missing '}' or illegal start of expression
答案1
得分: 2
int[] result = {max, max, max};
上述代码可以编译通过,因为编译器能够识别类型。
return {first, first, first};
上述代码无法编译通过,因为编译器无法确定类型。
应该修改为:
return new int[] {first, first, first};
或者,如果你想将其赋值给变量,仍然需要使用:
result = new int[] {first, first, first};
英文:
int[] result = {max, max, max};
The above compile because the compile knows the type.
return {first, first, first};
The above doesn't compile because the compiler doesn't know the type.
It should be:
return new int[] {first, first, first};
Or, if you want to assign it to a variable you still need to use:
result = new[int] {first, first, first};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论