Boolean not applying correctly [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Alrighty, so I have a program that is supposed to take the first name of the customer, and regardless if the letters in the name are capitalized or lower case, if they are Mike or Diane, it sets the discount to being true and then later on applies the discount. By default discount = false.
Heres getting the name and setting discount to true:
if (firstName == "Mike" || firstName == "Diane")
{
discount = true;
}
And here's later on when I'm trying to apply the discount and lower the cost:
if (discount == true)
{
System.out.println("You are eligible for a $2.00 discount!");
cost = cost - (2.00);
}
However the problem is that when I use Mike or Diane, whether capitalizing or not, it simply does not apply the discount to the price. It compiles and runs, it just doesn't apply the discount.

Use .equals(...) to compare String values:
"Mike".equals(firstName)
== compares the references of Java Objects. It's perfectly fine to use == to compare primitive data types values (ex. boolean, int, double, etc.).
If you want to ignore the case of the characters, then use .equalsIgnoreCase(...):
"Mike".equalsIgnoreCase(firstName)
Check out the String API, it has a lot of useful methods.

You should not use == (reference equality) for determining String equality, luckily there is an String#equalsIgnoreCase(String) method.
boolean discount = ("Mike".equalsIgnoreCase(firstName) ||
"Diane".equalsIgnoreCase(firstName));

you can use equalIgnoreCase Method
"Mike".equalsIgnoreCase(firstName)
like
if(firstName.equalsIgnoreCase("Mike") || firstName.equalsIgnoreCase("Diane"))
{
discount = true;
}

== compares the reference of the strings. You can use equals:
Solution:
if(firstName.equalsIgnoreCase("Mike") || firstName.equalsIgnoreCase("Diane"))
{
discount = true;
}
Tip:
Nevertheless, it is better to write "Mike".equalsIgnoreCase(firstName) instead of firstName.equalsIgnoreCase("Mike"), because you are sure that Mike is not null. firstName.equalsIgnoreCase("Mike") can throw a NullPointerException if firstName is null.

Related

Multiplying certain value in array based on certain condition in another array and storing value in a new array?

I am creating a program based on arrays that helps calculate the stipend for a number of tutors who assist students with their skills. The program takes in the number of tutors, then proceeds with the tutors name, asks how many students that tutor has assisted and then asks what degree level the tutor has (BS, MS, PhD). The tutor will be payed a different amount of money based on the degree level they have. So if the first tutor (Bill) has taught 5 students and has a PhD (which is $20 per student), then he will be payed $100.00 and, so on and so forth for the other tutors (MS = 15.00 per student, BS = 9.50 per student).
My problem is that when I have entered all the data, I just get 0.0 for the pay column and 0.0 for the total stipend. What I am trying to do is based on the degree entered in the degree array, you multiply the taught array (aka the number of students taught) by the amount of money per student, and then store that number in a new array called stipend. I have re-arranged, re-named, and done about everything I can think of to try and get the stipend to show up but I am running out of options and becoming very frustrated. So if anyone could please help me it would be greatly appreciated.
for(int pay=0; pay<numOfTutors; pay++) {
if (degree[pay] == "BS") {
stipend[pay] = taught[pay] * 9.50;
}
else if (degree[pay] == "MS") {
stipend[pay] = taught[pay] * 15.00;
}
else if (degree[pay] == "PhD") {
stipend[pay] = taught[pay] * 20.00;
}
sum+=stipend[pay];
}
The problem is that you are using the == operator, instead of the .equals() method, to check for string equality. You should change the lines of the form
degree[pay] == "some_string"
to
degree[pay].equals("some_string")
Or, if you want case insensitive matching, you could use
degree[pay].equalsIgnoreCase("some_string")
Here's what's going on: when you write degree[pay] = "some_string", you are checking for reference equality, which will not work for what you are doing, because a constant string and a generated string will not have equal references. The .equals() method will check for equal values, which is what you want.
Use String#equals to compare String content. The == operator is used to compare Object references. Because the references of the 2 values being compared are not equals, then none of the pay adjustments for the array stipend take place. Replace
if (degree[pay] == "BS") {
with
if (degree[pay].equals("BS")) {
Similarly for "MS" and "PhD" String checks.

if statement with integers [duplicate]

This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber

java if statement not breaking the "for loop" [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am newbie in java but I think I have done well teaching myself in these few weeks. But now I am stuck at this loop.
Here is a method from one of my class. To help me debug, I have added "myString" string and "syntax" list inside this method to demonstrate what is happening and to keep it simple, at least for now.
public void getIndex(){
String myString = "2 2 + 3 5";
String[] syntax = myString.split(" ");
for (int index = 0; index < syntax.length; index++){
System.out.println("current index is: " + index);
System.out.println("It has: " + syntax[index]);
// these print statements are made to help me debug
if (syntax[index] == "+"){
indexNeeded = index;
break;
}
}
System.out.println("Index Needed: " + indexNeeded);
As you can see inside the loop, I want to break the "for loop" when the element of the list, "syntax" is "+".
(I am showing "+" here but it can be anything in the actual program.)
Here is the output, when run this method:
current index is: 0
It has: 2
current index is: 1
It has: 2
current index is: 2
It has: +
current index is: 3
It has: 3
current index is: 4
It has: 5
Index Needed: 0
The loop should have stopped when it found "+" but it seems that "if statement" is not working at all, and hence "indexNeeded" hasn't changed.
It's a simple method but what am I doing wrong here?
You're trying to compare strings with ==. That doesn't work, you need to use .equals():
change:
syntax[index] == "+"
to
syntax[index].equals("+")
== only returns true when both objects refer to the same instance. equals() will return true when the contents of the string are the same. This is what you want.
Replace
if (syntax[index] == "+"){
with
if (syntax[index].equals("+")){
When you are trying == it comparing the references and syntex[index] is not referring to same location where literal "+" is. So they are not equal.
// If syntax[index] get '+' value from somewhere but not literal
if(syntax[index] == "+" ) // is false
// right way is
if(syntax[index].equals("+")) // is true
// If syntax[index] get '+' value from literal
syntax[index] = "+";
if(syntax[index] == "+" ) // is true
// This approach is faster but has mentioned above has limitations.
When you do equals it actually compares the content.
You should write:
syntax[index].equals("+")
"+" is a reference to a String, and syntax[index] is another. But here you want to compare the objects themselves, not their references.
If you take two objects a and b of whatever class, a == b will test that the references are the same. Testing that they are "the same" is written a.equals(b).
You should read Java's .equals() documentation carefully, it is a fundamental part to understand.
for String, you need to do
syntax[index].equals("+")
If you want to compare the value of a String you need to use .equals() but if you want to compare references you use the operator ==. That a common mistake with newbies.
Take a minute and see the difference between:
syntax[index] == "+"
and
"+".equals(syntax[index])
it that order you don't allow possible null pointer in syntax[index]
Here's a fun, educational way to fix your problem. Add a call to String.intern() to your method and it will work fine. Amaze your friends! :)
public int getIndex()
{
String myString = "2 2 + 3 5";
String[] syntax = myString.split(" ");
int indexNeeded = -1;
for (int index = 0; index < syntax.length; index++)
{
System.out.println("current index is: " + index);
System.out.println("It has: " + syntax[index]);
// these print statements are made to help me debug
if (syntax[index].intern() == "+")
{
indexNeeded = index;
break;
}
}
return indexNeeded;
}
Note that it is better to return a value from a method than it is to use variables with class scope. Class-scoped variables should be reserved for data that can be considered a property of the object. indexNeeded doesn't meet that description, and it's a poor name for an int - it sounds like it should be a boolean.
Equality checks in Java come in two forms.
The equality operator "==" checks to see if two variables refer to the same object. In your case, this test fails because, though their content is the same, you're referring to two different string objects.
The .equals() method is available on every Java object and provides extensible equality checking. In the case of Strings, consider the following:
"+".equals("+") // evaluates to true
going back to the equality operator:
"+" == "+" // evaluates to false
See this page for more detail.
Use return; instead of break;
it works for me

Conditional with number1 == number2 (of type Long) is never true?

this code is supposed to list recent calls with recent same nos skipped but they are being displayed, please help
//code
Long number0=(long) 0;
// loop through cursor
while(mCallCursor.moveToNext()){
Long number1 = mCallCursor.getLong(0);
if(number1==number0)
continue;
else
number0=number1;
if(mCallCursor.getString(2)!=null){
String name = mCallCursor.getString(2);
System.out.println(name);
}
else
System.out.println(number1);
}
Instead of
if(number1==number0)
use
if(number1.equals(number0))
Two Long values can satisfy equals without being ==.
The main reason why it is not working is that Long 's are objects and == operator works as it is testing equalities of two objects not the long values stored in these objects. On the other hand a long is not an object but a primitive.
if((long)number2 == (long)number1)
shall work as well.

Checking values in boolean array (Java)

I am having som slight difficulties with the following problem.
I have initialized a boolean array called numberArray with 31 indexes. The user is supposed to enter 5 digits between 1 and 30, and each time a digit is entered, the program is supposed to set the proper index to true. For instance, if I enter 5 then:
numberArray[5] = true;
However, if the user enters the value 5 a second time, a message should be given to the user that this number has already been entered, and so the user has to choose a different value. I have tried to create a loop as follows:
public void enterArrayValues() {
for(int i = 1; i < 6; i++) {
System.out.print("Give " + i + ". number: ");
int enteredNumber = input.nextInt();
while (numberArray[enteredNumber] = true) {
System.out.println("This number has already been chosen.");
System.out.print("Give " + i + ". number again: ");
enteredNumber = input.nextInt();
}
numberArray[enteredNumber] = true;
}
}
The problem is that when I run the program, I automatically get the message "The number has already been chosen" no matter what I enter. Even the first time I enter a number. I don't get this. Isn't all the values in the boolean array false by default?
I would greatly appreciate it if someone could help me with this!
while (numberArray[enteredNumber] = true) {
make that
while (numberArray[enteredNumber] == true) {
or change to
while (true == numberArray[enteredNumber]) {
or simply drop the ==true
while (numberArray[enteredNumber]) {
while (numberArray[enteredNumber] = true)
is an assignment, use the == operator or simply while (numberArray[enteredNumber]).
I know its hard to get into while you are still learning, but the earlier you start coding in an IDE the better off you will be. This is one tiny example of something an IDE will warn you about.
Change the while line to:
while (numberArray[enteredNumber]) {
Because mistakenly entering = instead of == is a common mistake, some people always code this type of statement in the following manner:
while (true == numberArray[enteredNumber]) {
With this format, if you use = instead of ==, you will get a compiler error.
Also, if you use a type of static analysis tool such as PMD, I believe you get a warning for the statement that you originally wrote.
Thde problem is in the condition of the while loop - you are using the assignment operator (=), whereas you are supposed to use the equality comparer (==). This way the loop condition is always true, because you are assigning true to the indexed field.
I hope this will work :-) .
The condition in the while loop should be while (numberArray[enteredNumber] == true). You're using the assignment operator =, not the comparison operator ==. Assignment is an expression that returns the assigned value, which is true in your case.

Categories

Resources