Break DO While Loop Java?

前端 未结 3 1029
心在旅途
心在旅途 2020-12-10 16:10

I\'m new into JAVA and I\'m not sure how to break a the DO WHILE loop that I use in my code below? I thought I could enter -1 to break or all other numbers to continue the l

3条回答
  •  爱一瞬间的悲伤
    2020-12-10 16:40

    You need to use .equals() instead of ==, like so:

    if (value.equals("-1")){
        control = 0;
    }
    

    When you use == you're checking for reference equality (i.e. is this the same pointer), but when you use .equals() you're checking for value equality (i.e. do they point to the same thing). Typically .equals() is the correct choice.

    You can also use break to exit a loop, like so:

    while( true ) {
        String value = JOptionPane.showInputDialog( "Enter a number or -1 to stop" );
        System.out.println( value );
        if ( "-1".equals(value) ) {
            break;
        }
    }
    
    • For more on == vs .equals() see Difference Between Equals and ==

提交回复
热议问题