Modifying Arrays
Parte de la sección Fundamentos del Journey de Java de Coddy — lección 60 de 73.
Además de acceder a los elementos de un array, también puedes modificarlos. Para modificar un elemento específico en un array, puedes asignarle un nuevo valor usando su índice.
Aquí hay un ejemplo:
String[] my_array = {"apple", "banana", "cherry"};
my_array[1] = "orange";
System.out.println(my_array[0] + ", " + my_array[1] + ", " + my_array[2]);Salida:
apple, orange, cherrybanana se cambió a un orange
Desafío
FácilCrea un método llamado <strong>changeElement</strong> que recibe 3 argumentos:
- Primer argumento es un array
- Segundo argumento es un índice
- Tercer argumento es un nuevo elemento
El método devolverá un array modificado cambiando el elemento en el índice que se almacena en el segundo argumento con el valor en el tercer argumento.
Por ejemplo con los siguientes argumentos: changeElement<strong>(</strong>new String[] {"1", "2", "3"}, 0, "9") el método devolverá [9, 2, 3]
Hoja de referencia
Para modificar un elemento de un array, asigna un nuevo valor usando su índice:
String[] my_array = {"apple", "banana", "cherry"};
my_array[1] = "orange"; // Cambia "banana" a "orange"Pruébalo tú mismo
import java.util.Scanner;
public class Main {
public static String[] changeElement(String[] arr, int index, String newElement) {
// Escribe el código aquí
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String textArray = scanner.nextLine();
int index = scanner.nextInt();
scanner.nextLine();
String newElement = scanner.nextLine();
String[] arr = textArray.split(",");
String[] modifiedArr = changeElement(arr, index, newElement);
for (int i = 0; i < modifiedArr.length; i++) {
System.out.print(modifiedArr[i] + " ");
}
}
}Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.
Todas las lecciones de Fundamentos
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 411Arrays Basics
Declaring ArraysAccessing ElementsModifying ArraysArray MethodsRecap - Product ArrayRecap - Reversed Array3Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else