How to change item in an Arraylist index?

Asked

Viewed 3,277 times

2

I’m having trouble with this array exercise:

a) Create the Blocodenotes class that has an attribute ArrayList<String> called notes. Create methods to insert, remove and fetch notes. Create a method that prints all notes.

b) Create the Appblock class, with a main method, and a menu that
1) Enter a note,
2) Remove a note,
3) Change a note,
4) List all notes and
5) Exit from the system.

What I’ve done so far:

import java.util.ArrayList;
import javax.swing.JOptionPane;


public class BlocoDeNotas{

  private ArrayList<String> notas = new ArrayList<String>();

  public void inserirNota (String nota){
   notas.add(nota);
  }


  public int buscarNota (String nota){
   for(int i=0; i < notas.size(); i++){
      if(notas.get(i).equals(nota))
        return i;            
   }
   return -1;  
  }
  public boolean removerNota(String nota){
   int posicao = buscarNota(nota);
   if (posicao >= 0){
      notas.remove(posicao);
      return true;
   } 
   return false;
  }

  public void listarNotas(){
   for (String minhaNota:notas){
      System.out.println(minhaNota);
   }

  } 


}

It is missing to make the method to change a note, requested in the statement. How do I do this?

1 answer

3

Create a method that receives the new note and index that this new note will replace, and use the method ArrayList.set(int index, E element) to make the exchange:

public void alterarNota(int indice, int novaNota){

    if(indice >= 0 && indice < notas.size()){

        notas.set(indice, novaNota);
    } 
}

Parole is required to prevent burst ArrayIndexOfBoundException by access to non-existent indexes in the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.