我在plusTen()方法中复制了原始数组,为数组中的每个值添加了10,我现在尝试在main方法中调用newArray然后打印它。它有一些简单的东西我可以忽略。
public class mod4 {
public static void main(String[] args) {
int min;
int max;
// Creates array
int[] array = new int[10];
//Fills array
array[0] = 10;
array[1] = 25;
array[2] = 34;
array[3] = 16;
array[4] = 86;
array[5] = 13;
array[6] = 47;
array[7] = 50;
array[8] = 26;
array[9] = 75;
//Prints original array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
//Prints Minimum
System.out.println("Mimimum: " + minNum(array));
//Prints Maximum
System.out.println("Maximum: " + maxNum(array));
int[] newArray = plusTen(int array
);
//Print new array
for (int i = 0; i < newArray.length; i++) {
System.out.println(newArray[i] + " ");
}
}
//Finds Minimum value
public static int minNum(int[] array) {
int min = array[0];
for (int i = 1; i > array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
//Finds maximum value
public static int maxNum(int[] array) {
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
//Adds ten to values in array
public static int plusTen(int[] array) {
//makes copy of array
int[] newArray = new int[array.length];
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
//adds 10 to values in new array
for (int i = 0; i < newArray.length; i++) {
newArray[i] = newArray[i] + 10;
}
}
}
答案 0 :(得分:1)
你有一些错误:
plusTen
应该返回int[]
,而不是int
。return
语句。int
时,plusTen(array)
不属于
醇>
试试这个:
//...
int[] newArray = plusTen(array);
//...
public static int[] plusTen(int[] array) {
//makes copy of array plus 10
int[] newArray = new int[array.length];
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i] + 10;
}
return newArray;
}
答案 1 :(得分:0)
您无需创建新阵列
public static void main(String[] args) {
.....
//Prints original array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
plusTen(array);
System.out.println("---Changed Array ----");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
}
public static void plusTen(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = array[i] + 10;
}
}