java—为什么break语句不从while循环中断?

tjvv9vkg  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(452)

为什么这个代码段没有从while循环中断(请参阅下面的代码):我所期望的是,当我键入单词“end”时,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);
    }
}

在main方法中(在这里未显示的另一个类中),我先调用方法“filllist”,然后调用“displaylist”,然后调用“deletelist”

fruv7luv

fruv7luv1#

代替 element == "end" 具有 element.equals("end")

4c8rllxm

4c8rllxm2#

说明:要检查字符串变量之间的相等性,需要使用 .equals() 功能
解决方案

element.equals("end")

相关问题