Nathan Hood February 2016

Java Calculation Error

I've been writing a program for my uni course and I'm stumped on something that is probably ridiculous.

Here's a bit of my code

// International Calls Selection

            System.out.println("Would you like to include international calls?");
            System.out.println("1. Include");
            System.out.println("2. Do not Include");
            int intCallChoice = keyboard.nextInt();
            boolean intChoice = true;

            if (intCallChoice == 2)
            {
                intChoice = false;
            }

This part takes the input from the user as you can see, then in my contract class I have a price calculator method which goes like this:

    if (intChoice = true)
    {
        priceOfContract *= 1.15;
    }

However, the result always ends up being a 15% increase, no matter if I select to include International Calls or to not include them?

Answers


Juned Ahsan February 2016

if (intChoice = true)

will always be true because you are using assignment(single =) and not equals(double ==)

Your condition should be

if (intChoice == true)

or simply

   if (intChoice) // for boolean check


Abdelhak February 2016

Try to use == instead of = like this:

 if (intChoice == true){

The = it is used for assign, but == it's used to check equality. Or use just:

  if (intChoice){


jonk February 2016

As others have said you need to use == to compare values, however since your variable is a boolean you can shorten this if statement even further:

if (intChoice) {
    priceOfContract *= 1.15;
}


Lourenco February 2016

 if (intChoice = true)

Is a condition, and when you want to compare the intChoice variable value with true, you must use two equal signs (==), the same way you did in:

if (intCallChoice == 2)

If you use only one equal sign you are changing the value of the intChoice variable to true and the condition will be allways

if(true)

Which means for any type of calls the priceOfContract will be multiplied by 1.15.

Post Status

Asked in February 2016
Viewed 3,780 times
Voted 14
Answered 4 times

Search




Leave an answer