J.McIntosh
J.McIntosh

Reputation: 1

Is it possible to use a boolean expression in this manner?

I am currently learning java script and attempting new things, for example I wish to see if I can set a boolean expression to end if it detects a starting number through an ending number.

Or in other terms what I'll want is 3 through 8. I will make it clear I am using netbeans IDE.

Within my last else if statement, I want it to end the asking process. I am hoping it is a simple fix, but I can not think of anything that will accomplish this unless I create a lot more else if statements.

Scanner input = new Scanner(System.in);

int[][] table;

boolean stopasking = true;



    while (stopasking = true){

    System.out.println("Let's make a magic Square! How big should it be? ");
    int size = input.nextInt();


    if (size < 0)
    {
        System.out.println("That would violate the laws of mathematics!");
        System.out.println("");
    }
    else if (size >= 9)
    {
        System.out.println("That's huge! Please enter a number less than 9.");
        System.out.println("");
    }
    else if (size <= 2)
    {
        System.out.println("That would violate the laws of mathematics!");
        System.out.println("");
    }
    else if (size == 3)
    {
        stopasking = false;
    }


    }

Upvotes: 0

Views: 64

Answers (1)

Andrea Sindico
Andrea Sindico

Reputation: 7440

You have used the assignmnent operator = you should use == instead

also the condition size<=2 holds when size<0 so you can use one if for both

while(stopasking){
    if (size <= 2) {
        System.out.println("That would violate the laws of mathematics!\n");
    } else if (size >= 9){
       System.out.println("That's huge! Please enter a number less than 9.\n");
    } else if (size == 3){
        stopasking = false;
    }
 }

you can use the boolean expression in this way, as condition to exit from a loop. Some would say it is a more elegant solution than break.

Upvotes: 1

Related Questions