How to change item in an index of an ArrayList?

2

I'm having trouble with this array exercise:

  

a) Create the class BlockNotes that has as attribute a    ArrayList<String> called notes. Create methods to insert, remove, and   look for notes Create a method that prints all the notes.

     

b) Create the AppBloco 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 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);
   }

  } 


}

You need to make the method to change a note, request in the statement. How do I do that?

    
asked by anonymous 26.05.2017 / 02:38

1 answer

2

Create a method that receives the new note and index that this new note will replace, and use the #

public void alterarNota(int indice, int novaNota){

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

        notas.set(indice, novaNota);
    } 
}

A conditional is required to prevent it from popping ArrayList.set(int index, E element) by accessing non-existent indexes in the list.

    
26.05.2017 / 02:52