0

why doesn't this code segment break from the while loop ? (see code down below) : what i expected is that when i type the word "end" the while loop breaks. but it doesn't.

if(element=="end")
{
    break;
}

here is the java class i used:

public class Something {
        
    private List<String> aList = new ArrayList<String>(); 
    private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
    /**
     * the method "fillList" fills an ArrayList with a certain number of items (this number is defined in the parameter) 
     * the method "deleteList" deletes the selected items (selected using BufferedReader.readline() ) from the ArrayList 
     * until you enter the word "end", which breaks from the loop
    */
    public void fillList(int nbElements)
    {
        System.out.println("you are going to append "+nbElements+" Elements" );
        for(int i=0;i<nbElements;i++)
        {           
            System.out.println("insert element N° "+(i+1) );
            try 
            {
                String element = br.readLine();
                this.aList.add(element);
            } 
            catch (IOException e) 
            {
                System.out.println("an error occured");
            }                       
        }   
    }
        
    public void deleteList() 
    {       
        while(true)
        {       
            System.out.println("choose the item to delete");                                            
            try 
            {
                String element = br.readLine();
                if(element=="end")
                {
                    break;
                }
                this.aList.remove(element);
                this.displayList();
            } 
            catch (IOException e) 
            {           
                System.out.println("an error occured");
            }           
        }
    }
    
    
    public void displayList()
    { 
        System.out.println(this.aList);
    }
}

in the main method (inside another class not shown here), i called the methods "fillList" then "displayList" and then "deleteList"

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • There is no `while` loop, it's a `for` loop. There's no `break` statement in the loop. You really should show the actual code you are having issues with, your example is pretty terrible and I'm having a hard time understanding what the problem actually is. – markspace Jul 10 '21 at 14:16

1 Answers1

1

Replace element == "end" withelement.equals("end")

SAL
  • 547
  • 2
  • 8
  • 25