如何在整型数组中添加整数?(Java)

huangapple go评论71阅读模式
英文:

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

array coding practice

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

huangapple
  • 本文由 发表于 2020年10月19日 09:00:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64419848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定