我需要将数组中的所有值多个乘以3000,这反过来会创建一个新数组,我将用它从另一个数组中减去。我已经尝试创建一个单独的方法来为我做这个但是我在乘法数组中回来的是一堆数字和符号奇怪吗?
这是我写的代码
public static void main(String[] args)
{
int numberOfTaxpayers = Integer.parseInt(JOptionPane.showInputDialog("Enter how many users you would like to calculate taxes for: ");
int[] usernumChild = new int[numberOfTaxPayers];
for (int i = 0; i < usernumChild.length; i++)
{
usernumChild[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter number of children for user "+ (i+1) +": "));
}//this for loop finds out the number of children per user so we can later multiply each input by 3000 to create an array that determine dependency exemption for each user
int[] depndExemp = multiply(usernumChild, 3000);//this was the calling of the multiply method... somewhere here is the error!!
}//end main method
public static int[] multiply(int[] children, int number)
{
int array[] = new int[children.length];
for( int i = 0; i < children.length; i++)
{
children[i] = children[i] * number;
}//end for
return array;
}//this is the method that I was shown in a previous post on how to create return an array in this the dependency exemption array but when I tested this by printing out the dependency array all I received were a jumble of wrong numbers.
答案 0 :(得分:4)
在您的示例中,您将子数组相乘但返回新数组。您需要将您的新数组乘以子数组。
1 public static int[] multiply(int[] children, int number)
2 {
3 int array[] = new int[children.length];
4 for( int i = 0; i < children.length; i++)
5 {
6 array[i] = children[i] * number;
7 }//end for
8 return array;
9 }
您获得奇怪符号的原因是因为您返回的是未初始化的值。数组本身在第3行分配,但此时数组的每个索引都没有初始化,所以我们真的不知道那里有什么值。
答案 1 :(得分:3)
使用Java 8流可以很简单:
public static int[] multiply(int[] children, int number) {
return Arrays.stream(children).map(i -> i*number).toArray();
}
答案 2 :(得分:1)
您需要更改
children[i] = children[i] * number;
到
array[i] = children[i] * number;
答案 3 :(得分:1)
您实际上不必在方法中创建新数组(并且您也将返回旧数组而不做任何更改)。所以就这样做
public static int[] multiply(int[] children, int number) {
for(int i = 0; i < children.length; i++) {
children[i] = children[i] * number;
}
return children;
}
答案 4 :(得分:1)
如果我理解你的问题:
children[i] = children[i] * number;
应改为
array[i] = children[i] * number;
考虑到您要返回array
,而不是children
。
答案 5 :(得分:0)
在你的第二个for循环中它应该是:
for(int i = 0; i < children.length; i++){
array[i] = children[i] * number;
}//end for
同时确保children[i]
的所有值都低于((2^31 - 1)/number) +1