Home » Java » java – How do I properly nest this If statement-Exceptionshub

java – How do I properly nest this If statement-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m capturing user input but restricting them between 1-100. I’m having some difficulty nesting this if statement correctly.
Goal:
user can input any amount between 1-100
if not, it sets automatically to 0.
I print the results at the end

    // if statement to restrict use to 1-100
    hatNumber = in.readInt("How many beaver hats would you like?: \n");
    if (hatNumber <= 0 && hatNumber > 100) {
        System.out.println("Hats = " + hatNumber);
    } else {
        hatNumber = 0;
    }
    photoNumber = in.readInt("How many photographs would you like?: \n");
    if (photoNumber <= 0 && photoNumber > 100) {
        System.out.println("Photographs = " + photoNumber);
    } else {
        photoNumber = 0;

        jarNumber = in.readInt("How many Jars of maple syrup?: \n");



    if (jarNumber <= 0 && jarNumber > 100) {
            System.out.println("Jars = " + jarNumber);

        } else {
            jarNumber = 0;
            {

                System.out.println("Hats = " + hatNumber);
                System.out.println("Photographs = " + photoNumber);
                System.out.println("Jars = " + jarNumber);
How to&Answers:

First of all, If you are expecting a logic “User can input any amount between 1-100 if not, it sets automatically to 0 “. You should change if else check to

if (hatNumber > 0 && hatNumber <= 100) {
        System.out.println("Hats = " + hatNumber);
} else {
        hatNumber = 0;
}

Final code will look like.

    hatNumber = in.readInt("How many beaver hats would you like?: \n");
    if (hatNumber > 0 && hatNumber <= 100) {
        System.out.println("Hats = " + hatNumber);
    } else {
        hatNumber = 0;
    }
    photoNumber = in.readInt("How many photographs would you like?: \n");
    if (photoNumber > 0 && photoNumber <= 100) {
        System.out.println("Photographs = " + photoNumber);
    } else {
        photoNumber = 0;
        jarNumber = in.readInt("How many Jars of maple syrup?: \n");
        if (jarNumber > 0 && jarNumber <= 100) {
            System.out.println("Jars = " + jarNumber);
        } else {
            jarNumber = 0;
        }
    }
    System.out.println("Hats = " + hatNumber);
    System.out.println("Photographs = " + photoNumber);
    System.out.println("Jars = " + jarNumber);

Answer:

 if (hatNumber <= 0 && hatNumber > 100) 

This condition can never be true in any case. you shold use the following condition

 if (hatNumber > 0 && hatNumber < 100) {
    System.out.println("Hats = " + hatNumber);
 }

Answer:

you’re missing a close brace on the line after

photoNumber = 0;