Java Calculation Error - java

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?

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

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){

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;
}

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.

Related

How to put 2 condition in one statement actiolistener in java? [duplicate]

I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}

Is it possible to include a = sign in the "if ()"?

I wrote a line to add a total up the total value
int totalValue = value1 + value2 + value3;
Now I want to use an if statement to write if (totalValue = 200); but it gives me an error saying "Cannot convert from an int to a boolean type".
What should I do because I want to have four possible outcomes using else if();
System.out.println();
if (totalValue == 200)
= is for assigning values, == is for comparing values.
The = operator in Java only does assignment; you want to compare totalValue to 200, so you should use the == comparator operator.
if(totalValue = 200){
...
}
Do note that you shouldn't have a semicolon after an if statement, since then Java will basically ignore the if.
The = sign is the assignment operator.
Doing if(totalValue = 200) will actually assign 200 to totalValue.
What you need is the == operator
if(totalValue == 200)
{
System.out.println("200");
}
else if (totalValue == 100)
{
System.out.println("100");
} //...
Putting the line terminator at the end of if(totalValue == 200);
will terminate the conditional statement. This means that the statements below it will not only execute if the condition evaluates to true.
Also, I find it good practice to always put {} after the if() even with just one statement to prevent issues with scoping. Here's a link to show how this can happen (and prevented) https://stackoverflow.com/questions/21999473/apples-goto-fail-security-bug
if you write if(totalValue = 19), it will evaluate if you can successfully assign 19 to totalValue.
Being successful or not, in Java is a Boolean, so it expects to evaluate a boolean.
The expression:
if((totalValue = 19) == True){ ... }
would be correct but also useless, in this case, because it will almost for sure assign successfully the value
if you wanna only check the value you must use ==
Yes, but equality is == and assignment is =. Also, don't end your if statement with a semicolon or you terminate the body of the if.
// if (totalValue = 200);
if (totalValue == 200) {
// Do stuff for when the value is 200
} else {
// Do stuff when the value is not 200
}
Like the others said, the '=' operator in Java is used to assign values. However (maybe a little off-topic), the assignment itself evaluates to the assigned value, which can be reused in a boolean expression.
This can be used like in this loop, where the result of readLine is stored and compared to null in a single expression:
int value;
while ((value = reader.read()) != -1) {
doSomething(value);
}

Do while loop comparing Strings

I'm trying to do a "do while" loop with a nested if statement. I'm trying to compare two possible values for a String variable "word". If !word.equals "deeppan or thin" do something, else do something. But its not liking me using the or || comparator .. Any suggestions would be welcome.
do {
word = scan.next();
if ( !word.equalsIgnoreCase( "Deeppan" || "thin" ) ) {
System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
} else {
break;
}
} while ( true );
equalsIgnoreCase takes a single string argument, not a logical expression. You can combine them with || or && though:
if (!word.equalsIgnoreCase( "Deeppan") && !word.equalsIgnoreCase("thin" ))
You have to do it like this:
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin")) {
Think about the || which i switched to &&, because the if should only be true, if the value is not the first AND not the second one!
This part is wrong, that's not how you use the boolean || operator, and anyway the logic is incorrect:
if (!word.equalsIgnoreCase("Deeppan" || "thin"))
It should be like this, comparison-operator-comparison, and notice the correct way to state the comparison for the effect you want to achieve:
if (!(word.equalsIgnoreCase("Deeppan") || word.equalsIgnoreCase("thin")))
Or equivalently, using De Morgan's laws (and easier to read and understand, IMHO):
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin"))
You have a few issues going on. First:
"Deeppan" || "thin"
is attempting to use the boolean "OR" operator to compare two strings. The "OR" operator can only compare boolean results and returns a boolean that is the result of the comparison:
System.currentTimeMillis() == 123455667 || object.equals(this) // both sides are boolean results.
true || false // returns 'false'
But let's pretend for a second that "Deeppan" || "thin" is OK (remember, it isn't) and the compiler knows that you want to compare the two strings. It still leaves the issue that the OR operator returns a boolean result (true or false), which you are then attempting to pass into the method equalsIgnoreCase on the word variable. equalsIgnoreCase takes a String argument, not a boolean. This is the second compilation issue. As has been pointed out, what you need is to check for the conditions separately and OR the result to get the final boolean
if("Deeppan".equalsIgnoreCase(word) || "thin".equalsIgnoreCase(word)) {
// do something
}
("Deeppan" || "thin")
is a boolean expression. equalisIgnoreCase takes a string. Therefore you need to make two seperate calls and OR the (boolean) results

Java boolean not behaving with breakpoints in if statement

Basically, this peice of code seems to behaving differently when I move the breakpoints
int checker = something.length(); /* something is the value of an edittext */
boolean badInput = false;
if(checker == 0)
{
badInput = true;
}
if(checker > 12)
{
badInput = true;
}
*1 if(badInput = false)
{
*2 /* A lot of
code to do
if the
input is GOOD */
}
else
{
/* Alert that the input is BAD */
}
When I enter a 2 digit number into the edittext with the first breakpoint (1), badInput gives false, as it should.
Here is the problem: when I do exactly the same with only the second breakpoint (2), the code goes onto the else statement, and alerts, even though the input is exactly the same.
Anybody know why this might be?
This:
if(badInput = false)
Should be:
if(badInput == false)
Or preferrably:
if (!badInput)
The first is performing an assignment, not a comparison. The overall result of the expression badInput = false is also the value assigned (false) so it will never enter the body of that if.
It's not really clear what you mean by entering data "with" a breakpoint, but fundamentally the problem is in your code.
You should have:
if(!badInput)
or
if(badInput==false)
(the first one is better)
Simple typo error,
if(badInput = false)
should be
if(badInput == false)
you want a compare not assign.
What you check boolean variable with == operator ?!!
You have to check as following :
if(!badInput) //for false value
or
if(badInput) //for true value

Why my parsing doesn't work?

I was asked for my homework to make a program wherein the user inputs a Roman numerals between 1-10 and outputs the decimal equivalent. Since I'll be getting a string in the input and an integer in the output, I parsed it, but it won't work. Any ideas why?
import java.util.Scanner ;
class Romans {
static Scanner s = new Scanner(System.in) ;
static String val = null ;
public static void main (String [] args)
{
System.out.print ("Enter a roman numeral between I to X: ");
String val = s.nextLine();
int e = Integer.parseInt(val);
}
static int getRoman (int e)
{
if (val = "I"){
System.out.print ("1") ;
}else if (val = "II" ){
System.out.print ("2") ;
}else if (val = "III") {
System.out.print ("3") ;
} else if (val = "IV") {
System.out.print ("4") ;
} else if (val = "V"){
System.out.print ("5");
} else if (val = "VI") {
System.out.print ("6");
} else if (val = "VII") {
System.out.print ("7");
} else if (val = "VIII") {
System.out.print ("8");
} else if (val = "IX") {
System.out.print ("9");
} else if (val = "X") {
System.out.print ("10") ;
}
return val ;
}
}
Two points:
= is the assignment operator, not the equality-testing operator (==)
You shouldn't use == to test for string equality anyway, as it will only test for reference equality; use equals to test whether two string references refer to equal (but potentially distinct) string objects.
Additionally, you're trying to return a String variable as an int, and you're not even calling getRoman...
I think we can tell you that the correct way to compare Strings is using equals().
You're doing assignments, to compare primitive types you've to use ==, to compare String the equals method.
Example:
if (val.equals("I"))
But also val is not present in the method getRoman().
You are trying to parse val as an int, but its not, its a character.
For such a small sample of chars, its probably easiest to simply create a lookup table, index it on the char.
Are you getting any errors?
In your code, you never call the getRoman function. Also, you're using the assignment operator = instead of the comparison operator "I".equals(val) for example.
String comparsion should be done with equals(String str) method instead of == comparison.
PS. You have = instead of == anyway.
The following statement is an assignment:
val = "I"
That is definitely not what you want to do here.
A comparison is done with the double equals, but double equals (==) compares references but you do not want to do that here either.
You want to use the equals method.
if (val.equals("I")) ...
Make those change everywhere and see how it works for you.
ACtually your main trouble comes from string comparison. In java, = is meant to assign values to variables, == is meant to compare values of primitive types and equals is the way to compare objects, especially for strings.
An alternative to using equals can be to use the JDK internal pool of strings, in this case, you could use == as a comparator.
In your case of parsing roman language numbers, you could also consider using a hashmap to store and retrieve effectively the parsed values of numbers. If you have thousands of comparisons like this to make, then go for identityhashmap.
And last, if you want to do real parsing for all roman numbers, not only the first ones, then you should considering using an automata, i.e. a state machine to parse numbers in a somewhat recursive way, that would be the more efficient model to apply to your problem.
The last 2 remarks are more oriented towards software algorithms, the first two ones are more oriented towards java syntax. You should start to know the syntax before going higher level optimizations.
Regards,
Stéphane
Aside from what was said above about how your String comparison should use the equals( ... ) function - for example,
if ( val.equals("VII") )
you also need to provide a return value for your function called getRoman. This function was declared as a function that returns an integer value to the caller, but in the implementation that you have provided, there are no return values (only System.out.println( ... )).
Also, you aren't inputting the correct parameter type - from what it looks like, your function is checking a String to see if it is a certain Roman numeral. So the correct function header would look like this:
public static int getRoman(String val)
Also, make sure you are actually calling this function in your main() - from what it looks like right now, you aren't even using the getRoman() function.
Hope this helps!

Categories