Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Question about if statements in Java

Hi everyone!

So, I am playing around with some if statements and logic in general. I am doing an exercise from a book. I have to make the program ask the user for a price - and the program should calculate the discount for the product based on the if statements. If the price is less than 128, the discount is 8%. If the price is equal to or higher than 128, the discount is 16%. This part I got right, so far so good. But then i thought: The program should tell the user if the price entered isn't allowed. Like if I type -934 it shouldn't calculate an 8% discount - it should tell me that only positive numbers are allowed and then ask for a new price. This below is my attempt to do that, but the program just gives me an error. Can someone please take a look and tell me what I'm doing wrong here?

import java.util.Scanner;

public class KilobyteDay {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter the original price: ");
        double originalPrice = in.nextDouble();
        in.close();
        double discountPrice = 0.0;

        //Discount 8% for prices below $128
        double discount1 = 0.92;
        //Discount 16% for prices greater than or equal to $128
        double discount2 = 0.84;

        if (originalPrice < 128 && originalPrice > 0) {
            discountPrice = originalPrice * discount1;
            System.out.println(discountPrice);
        } else if (originalPrice >= 128) {
            discountPrice = originalPrice * discount2;
            System.out.println(discountPrice);
        } else {
            System.out.println("Not a valid price");
            System.out.print("Please enter the original price: ");
            originalPrice = in.nextDouble();
            in.close();
        }
    }

}

2 Answers

Here is my attempt:

import java.util.Scanner;

public class KilobyteDay

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean isValid = false;

      double originalPrice;
      double discountPrice;
      double discount1 = 0.92; // discount 8% for prices below $128
      double discount2 = 0.84; // discount 16% for prices greater than or equal to $128

      do {
          System.out.print("Please enter the original price: ");
          originalPrice = in.nextDouble();
        // this is the validation you are asking for
          if (originalPrice > 0) {
            isValid = true;
          } else {
            System.out.println("Not a valid price");
          }
        } while(!isValid);

        if (originalPrice < 128) {
            discountPrice = originalPrice * discount1;

        } else {
            discountPrice = originalPrice * discount2;
        } 
            System.out.println(discountPrice);
            in.close();
    }

}

Note that I added all the declarations in one place to be cleaner, also removed the System.out.println from the if's an placed it after them so there is no code repetition, added the validation logic and moved the in.close to the end.

Thank you Pedro! That is a lot nicer - I'm still in the fase where I don't naturally see the best solution yet, so great to get some good solutions to something like this! :-)

Wait there is one thing I'm confused about here.. Why does it say } while(!isValid); - doesn't that mean "while isValid is false"?

This is the condition for the do while loop, so do all the code while isValid == false

In other words do all of the code in the loop until there is a valid number input by the user.

Yes it does, in spoken english would be something like: DO ask for original price WHILE it is NOT valid, so it will just stop asking once it is valid and everytime the user inputs a double there is the if that changes the boolean to true if it satisfies your condition/validation in that case the value being at least over 0. Do I make sense? :)

Aaaah okay, I thought the while part related to the if statements below - that's why I couldn't make sense of it. Thank you both again! :-)

Can you please also explain where in this code I could check for hasNextDouble(), to ensure that the input is an actual number? It doesn't work when I put it in the first if statement like this:

 do {
          System.out.print("Please enter the original price: ");
          originalPrice = in.nextDouble();
          if (originalPrice > 0 && in.hasNextDouble()) { //this still gives an error when inputting text instead of a number.
            isValid = true;
          } else {
            System.out.println("Not a valid price");
          }
        } while(!isValid);

The best way to check if the number entered is a double is to read it as a string and try to convert it into a double and handle the exception (if it is not a double) accordingly.

Scanner in = new Scanner(System.in);
String value = in.nextString();
int amount;

try { 
    amount = Double.parseDouble(amount);
} catch(Exception e) {
    System.out.println("The number entered is not a double!");
}

That makes sense, but I can't quite see how to use it in this program. Where should I put the try catch block?

I would do something along the lines of

import java.util.Scanner;

public class KilobyteDay {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean isValid = false;
        boolean isDouble = false;

        String value;
        double originalPrice = 0;
        double discountPrice;
        double discount1 = 0.92; // discount 8% for prices below $128
        double discount2 = 0.84; // discount 16% for prices greater than or
                                    // equal to $128
        while (!isValid) {
            do {
                System.out.print("Please enter the original price: ");
                value = in.next();
                try {
                    originalPrice = Double.parseDouble(value);
                    isDouble = true;
                } catch (Exception e) {
                    System.out.println("The value entered is not a double");
                    continue;
                }
            } while (!isDouble);
            // this is the validation you are asking for
            if (originalPrice > 0) {
                isValid = true;
            } else {
                System.out.println("Not a valid price");
            }
        }

        if (originalPrice < 128) {
            discountPrice = originalPrice * discount1;

        } else {
            discountPrice = originalPrice * discount2;
        }
        System.out.println(discountPrice);
        in.close();
    }

}

What you have works fine, except for the fact that it will throw an IllegalStateException. Previously in your class you closed the stream for 'in' by using in.close() and are trying to use it after you have closed the stream. All you have to do is move your in.close() to be the last executed statement in the main method. You should not close your stream until you are done with it. As such:

Note: You could also define a new scanner variable but uses more resources as there is overhead for defining variables. Closing your stream very last will be your best choice.

import java.util.Scanner;

public class KilobyteDay {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter the original price: ");
        double originalPrice = in.nextDouble();
        double discountPrice = 0.0;

        // Discount 8% for prices below $128
        double discount1 = 0.92;
        // Discount 16% for prices greater than or equal to $128
        double discount2 = 0.84;

        if (originalPrice < 128 && originalPrice > 0) {
            discountPrice = originalPrice * discount1;
            System.out.println(discountPrice);
        } else if (originalPrice >= 128) {
            discountPrice = originalPrice * discount2;
            System.out.println(discountPrice);
        } else {
            System.out.println("Not a valid price");
            System.out.print("Please enter the original price: ");
            originalPrice = in.nextDouble();
        }
        in.close();
    }
}

Now I will warn you that while this will solve your error you are being thrown it will not solve all your problems because after you enter another number the program will end with no other prompt. This can be solved easily using a loop.

Good luck and happy coding!

Dylan Beech

Thank you so much Dylan, that was a great answer! :-) I'm glad I wasn't too far of.