Artiems
Artiems

Reputation: 53

While code, Method, Int to boolean understanding

I'm reviewing some code for a college assignment and we've been given examples to assist us. I'm little confused on what the below is doing as it's using the assignment operator instead of the .equals or == method.

If I replace the code with the == (and create a local variable to compare it to) the code starts infinite looping and displaying out the default value.

 int select = 0;
 
  do {
    
        switch (select) {
            case 1:
                Problem();
                break; 
            default:
            System.out.println("Invalid");
            break;
            } 

    } while ((select = getSelection()) !=3);

 public static int getSelection () { 
(Return function here with has.nextInt and scanner class to receive input)
}

From my limited understanding, the above assigns "Select" to the value from the "getSelection" method, it's also stating do not accept inputs that are 3 e.g. System.exit0 at this point.

Have I understood correctly?

(Further example as requested) I would do something along the lines of:

int select = 0; 
int select1 = 0; 
    do {

    switch (select) {
        case 1:
            Problem();
            break; 
        default:
        System.out.println("Invalid");
        break;
        } 
 } while (select == select1);

I am attempting to think of a logical equivalent to the lecturers example but seem to be unable to do this without breaking the while loop.

Upvotes: 1

Views: 58

Answers (1)

Bohemian
Bohemian

Reputation: 424993

In java, (and other "C like" languages) the result of an assignment is the value assigned, ie this code:

do {
    // other code
} while ((select = getSelection()) !=3)

is the same as:

do {
    // other code
    select = getSelection();
} while (select != 3)

This style, known as in-line conditional, is generally considered a style to be avoided.

There is a checkstyle violation for it - see AvoidInlineConditionals

Upvotes: 4

Related Questions