英文:
How to add 1 to each value in an array (in Java)?
问题
以下是翻译的代码部分:
public int[] add1toEach(int[] nums) {
int[] array = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
array[i] = nums[i] + 1;
}
return array;
}
英文:
Here's the prompt:
Loop through an integer array adding one to each element. Return the resulting array. The array may be of any length including 0.
Here's what I have so far:
public int[] add1toEach(int[] nums) {
int[] array = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
nums[i]++;
}
return array;
}
It works with add1toEach[]
and add1toEach[-1]
but that's it. How do I get it to spit out [7, 7, 3]
if add1toEach[6, 6, 2]
is the input?
答案1
得分: 1
以下是您要求的翻译内容:
事实是,您没有将新添加的结果分配给数组,也没有正确添加它。
正确的代码是:
public static int[] add1toEach(int[] nums) {
int[] array = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
array[i] = nums[i] + 1;
}
return array;
}
这里发生的情况是,我们将1添加到项目中,然后将项目分配给一个相同的数组,但其中的项目都是空的。这会发生在数组的每个单独项目上,就像在for循环语句i < nums.length; i++
中所示。
这个工作示例:
public class MyClass {
public static void main(String args[]) {
int[] nums = {1, 2, 3};
int[] newnums = add1toEach(nums);
for (int i = 0; i < newnums.length; i++) {
System.out.println(newnums[i]);
}
}
public static int[] add1toEach(int[] nums) {
int[] array = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
array[i] = nums[i] + 1;
}
return array;
}
}
产生的输出是
2
3
4
英文:
The fact is that you aren't assigning the new added result to the array, nor are you adding it properly.
The proper code is:
public static int[] add1toEach(int[] nums) {
int[] array = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
array[i]=nums[i]+1;
}
return array;
}
What's happening here is that we add 1 to the item, then we assign the item to an identical array, but which the items are all empty. This happens to every single item of the array, as demonstrated in the statement in the for loop i < nums.length; i++
.
This working example:
public class MyClass {
public static void main(String args[]) {
int[] nums = {1, 2, 3};
int[] newnums = add1toEach(nums);
for(int i = 0; i < newnums.length; i++){
System.out.println(newnums[i]);
}
}
public static int[] add1toEach(int[] nums) {
int[] array = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
array[i]=nums[i]+1;
}
return array;
}
}
Produces
2
3
4
答案2
得分: -1
你的代码只返回未更改的 int[] array
。
由于你已经设置了数组的长度,你只需要使用位置 array[i]
来设置数组的值,以使值被分配并保持不变。
array[i] = nums[i]++;
英文:
What you're code doing is it only returns the untouched int[] array
.
Since you have set the length of your array, you just need to set values to your array with position array[i]
to make the values assigned and intact position.
array[i]=nums[i]++;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论