将1添加到数组中的所有奇数,并将1添加到另一个数组中的所有数字 [英] Add 1 to all the odd numbers in the array, and add 1 to all the numbers in another array
本文介绍了将1添加到数组中的所有奇数,并将1添加到另一个数组中的所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将1添加到数组中的所有奇数,并将1添加到另一个数组中的所有数字。我已尽力完成代码,但它没有运行,我不知道为什么?
I'm trying to add 1 to all the odd numbers in the array, and add 1 to all the numbers in another array. I've tried my best to complete the code but it doesn't run, I've no idea why?
public class MyProgram
{
public void start()
{
int[] oddUp = {3, 8, 4, 9, 5, 5, 23, 14};
int[] oneUp = {4, 8, 4, 10, 6, 6, 24, 24};
}
private void oddUp(int[] values)
{
for (int i = 0; i < oddUp.length; i++)
{
if (oddUp[i] % 3 == 0)
{
oddUp[i]++;
System.out.println(oddUp[i]);
}
else
{
return;
}
}
}
private void oneUp(int[] values)
{
for (int i = 0; i < oneUp.length; i++)
{
oneUp[i]++;
System.out.println(oneUp[i]);
}
}
}
推荐答案
更改以下代码
Change the Code as below
private void oddUpFunc(int[] values)
{
for (int i = 0; i < values.length; i++)
{
if (values[i] % 3 == 0)
{
values[i]++;
System.out.println(values[i]);
}
}
}
private void oneUpFunc(int[] values)
{
for (int i = 0; i < values.length; i++)
{
values[i]++;
System.out.println(values[i]);
}
}
通过在参数中传递数组来调用这些函数。
Call these functions by passing array in parameter.
oddUpFunc(oddUp);
oneUpFunc(oneUp);
嗨!...
我你的第一个功能有点变化......! :-)
Hi !...
Just I little bit of changes in your first function....! :-)
private void oddUp(int[] values)
{
for (int i = 0; i < values.length; i++)
{
// You need to test Odd number's Not as previous division by 3
if (values[i] % 2 != 0)
{
values[i]++;
System.out.println(values[i]);
// use of print here shows only updated numbers not all numbers in array if want to print all then use it outside of if...
}
// No need to reuturn as you want to add 1 to all odd number's in array....
}
}
干杯....... :-)
Hemant Singh(我的Asp.Net博客 [ ^ ])
这篇关于将1添加到数组中的所有奇数,并将1添加到另一个数组中的所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文