首页 > 解决方案 > 为什么break语句不会从while循环中中断?

问题描述

为什么这个代码段没有从 while 循环中中断?(见下面的代码):我期望的是当我输入“结束”这个词时,while循环会中断。但事实并非如此。

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

这是我使用的java类:

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);
    }
}

在主方法中(在此处未显示的另一个类中),我将方法称为“fillList”,然后是“displayList”,然后是“deleteList”

标签: javawhile-loopbreak

解决方案


替换element == "end"element.equals("end")


推荐阅读