Как добавить 100 в список элементов массива
В строке 4: я не могу понять, как сделать так, чтобы массив anArray добавлял 100 к каждому элементу после индекса 0 в цикле for? Инструкции приведены в комментарии. Есть предложения?
public static void main(String[] args) {
// LINE 1. DECLARE AN ARRAY OF INTEGERS
int[] anArray;
// LINE 2. ALLOCATE MEMORY FOR 10 INTEGERS WITHIN THE ARRAY.
anArray = new int[10];
// Create a usable instance of an input device
Scanner myInputScannerInstance = new Scanner(System.in);
// We will ask a user to type in an integer. Note that in this practice
// code WE ARE NOT VERIFYING WHETHER THE USER ACTUALLY
// TYPES AN INTEGER OR NOT. In a production program, we would
// need to verify this; for example, by including
// exception handling code. (As-is, a user can type in XYZ
// and that will cause an exception.)
System.out.print("Enter an integer and hit Return: ");
// Convert the user input (which comes in as a string even
// though we ask the user for an integer) to an integer
int myFirstArrayElement = Integer.parseInt(myInputScannerInstance.next());
// LINE 3. INITIALIZE THE FIRST ARRAY ELEMENT WITH THE CONVERTED INTEGER myFirstArrayElement
anArray[0] = myFirstArrayElement;
// LINE 4. INITIALIZE THE SECOND THROUGH THE TENTH ELEMENTS BY ADDING 100 TO THE EACH PRECEDING VALUE.
// EXAMPLE: THE VALUE OF THE SECOND ELEMENT IS THE VALUE OF THE FIRST PLUS 100;
// THE VALUE OF THE THIRD ELEMENT IS THE VALUE OF THE SECOND PLUS 100; AND SO ON.
for (int j=0; j < anArray.length; j++) {
if (anArray[j]!= anArray[0]){
anArray[j] += 100;
}
}
// LINE 5. DISPLAY THE VALUES OF EACH ELEMENT OF THE ARRAY IN ASCENDING ORDER BASED ON THE MODEL IN THE TOP-OF-CODE COMMENTS.
Arrays.sort(anArray); // Send our Anarray array to be sorted in ascending order by the sort() method
int i; // Define the counter for the loop. We can do it this way or inside
// the for loop, as we did in the preceding for loop.
for (i=0; i < anArray.length; i++) { // Loop, starting at 0 and adding 1 each time, until counter is less than array length.
System.out.println("Element at index " + i + ": " + anArray[i]);// print the numbers
}
}
}
Что я уже пробовал:
Я сделал все остальное для кода. Я не могу понять строку 4. пожалуйста, помогите. Спасибо.
Patrice T
Покажите вход и выход, которые вы хотите.
anArray[0] = myFirstArrayElement;
anArray[1] = ?
anArray[2] = ?
anArray[3] = ?