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

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

Related

Boolean not applying correctly [duplicate]

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.

If statement doesn't execute

I am creating a program that allows you to create a pie chart easily. In the method for removing a slice the if statement inside of a for loop doesnt execute and I cant figure out why this happens. Here is the removeSlice method:
public void removeSlice(Color color, float size, String displayText){
int num = 0;
System.out.println("Thing: " + color + " " + size + " " + displayText);
for(int i = 0; i < slice.size(); i++){
System.out.println("I: " + slice.get(i).color + " " + slice.get(i).size + " " + slice.get(i).text + " Current: " + i);
if(slice.get(i).color == color && slice.get(i).size == size && slice.get(i).text.equals(displayText)){
num = i;
System.out.println("It Works");
}
}
System.out.println(num);
slice.remove(slice.get(num));
totalSize -= size;
--current;
}
When trying to remove a slice the console output shows this
Thing: java.awt.Color[r=255,g=255,b=255] 100.0 Hey
I: java.awt.Color[r=0,g=0,b=0] 500.0 Hi Current: 0
I: java.awt.Color[r=255,g=153,b=153] 70.0 Hello Current: 1
I: java.awt.Color[r=255,g=255,b=255] 100.0 Hey Current: 2
I: java.awt.Color[r=153,g=153,b=0] 120.0 Hola Current: 3
0
as you see all of the values equal position 2's values in the ArrayList but still the if statement doesn't execute.
You are comparing colors with ==. Use equals instead. == checks if the objects refer to the same place in memory. You create two colors, but with the same content - then, you must use equals to check if the content match.
You need to modify slice.get(i).color == color to slice.get(i).color.equals(color).
You should use .equals() method to compare color object.
if(slice.get(i).color.equals(color) && slice.get(i).size == size && slice.get(i).text.equals(displayText)){
num = i;
System.out.println("It Works");
}
In addition to the == issue for Color, exact equality comparison for float can give problems. It will work if the values being compared were produced by exactly the same calculation, or if all calculations involved are exact. If not, there may be different rounding error leading to a very small difference in values that would be equal in real number arithmetic.
Small integer-valued floats such as 100.0 do represent the integer exactly, so that is probably not your current problem, but it could give you problems with different numbers.
As a Java Programmer, you should know about equals. Quite often this is what you really want.
You need to use equals() instead of == for the Color objects.
It's hard to say because we can't see whole source code but I think that your problem is here "slice.get(i).color == color". With == you tests if both variables reference the same object.
You should consider to use slice.get(i).color.equals(color) and you need to also implement equals, hashCode methods on that object
try to compare the different values with "equals", no with "=="

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

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.

I can't understand this programming code for psedorandom number generator for hashing

First of all I just begun learning Java and i can say it more challenging then C or python. I'm not very keen on programming to so I have hard time understanding how some codes works. This one in particular
public class Pseudo
{
final int a = 2;
final int c = 3;
int address;
String list[][] = new String [100][6];
public void AddRecord(String ID, String Name, String Course, String Address, String Email, String Contact)
{
address = (a * Integer.parseInt(ID) + c) % list.length;
if((Integer.parseInt(ID)<100000||Integer.parseInt(ID)>999999)||ID.length()==0 || Name.length()==0 || Course.length()==0 || Address.length()==0)
{
showMessageDialog(null,"The ID number should be in six digit and the particular field should not be empty","",ERROR_MESSAGE);
}
else{
if(list[address][0]!=null){
showMessageDialog(null,"Collison is occur, the same address is get. Recalculating...............","",WARNING_MESSAGE);
while(list[address][0]!=null)
{
address = (a * address + c) % list.length;
}
}
list[address][0] = ID;
list[address][1] = Name;
list[address][2] = Course;
list[address][3] = Address;
list[address][4] = Email;
list[address][5] = Contact;
showMessageDialog(null,"Student Information " + ID + " will be saved in address: " + address,"",INFORMATION_MESSAGE);
}
}
The confusion come when
address = (a * Integer.parseInt(ID) + c) % list.length;
if((Integer.parseInt(ID)<100000||Integer.parseInt(ID)>999999)||ID.length()==0 || Name.length()==0 || Course.length()==0 || Address.length()==0)
What does it mean. From what I understand from this code is that inside an IF statement you can have more then 1 condition. I'm no very sure since this is my first time seeing such a code.
The second is this
if(list[address][0]!=null){
showMessageDialog(null,"Collison is occur, the same address is get. Recalculating...............","",WARNING_MESSAGE);
while(list[address][0]!=null)
{
address = (a * address + c) % list.length;
}
}
list[address][0] = ID;
list[address][1] = Name;
list[address][2] = Course;
list[address][3] = Address;
list[address][4] = Email;
list[address][5] = Contact;
showMessageDialog(null,"Student Information " + ID + " will be saved in address: " + address,"",INFORMATION_MESSAGE);
If collision occurs the address of which it is stored should be altered using a psedorandom number generator again but what I can't grasped is
list[address][0]!=null.I am just baffle with this line. I know its job is change the address if collision happens but i don't know the exact mechanics of how this part is executed.
From what I understand from this code is that inside an IF statement you can have more then 1 condition.
Well, yes and no. You can construct complex conditions based on many smaller conditions, but ultimately the whole thing has to resolve to a single boolean true/false result.
Consider the condition in this case:
(Integer.parseInt(ID)<100000||Integer.parseInt(ID)>999999)||ID.length()==0 || Name.length()==0 || Course.length()==0 || Address.length()==0
Let's break that down into its components:
(
Integer.parseInt(ID)<100000 ||
Integer.parseInt(ID)>999999
) ||
ID.length()==0 ||
Name.length()==0 ||
Course.length()==0 ||
Address.length()==0
It's really just chaining together a bunch of comparisons into one big true/false statement. You can essentially read something like this as:
If (something) or (something else) or (another thing) then...
And each something can itself contain small somethings, etc. You can build as complex a logical condition as you want, grouping sub-conditions with parentheses, as long as the whole thing resolves to a single true/false result.
what I can't grasped is list[address][0]!=null
That is just checking if a particular value is null. That value is part of a nested (jagged) array. So you have a variable called list. That variable is an array. Each element in that array is, itself, also an array. So you end up with a kind of 2-dimensional array (but a jagged one, where any given sub-array doesn't have to be the same length as any other).
That specific piece of code looks into the list array, at the address index, and looks at the 0 index of that sub-array, and checks if that value is null.
First of all, understanding any code is much easier if it's properly formatted. All good IDEs have such a function, e.g. for Eclipse the shortcut is Ctrl+Shift+F, for IntelliJ IDEA Ctrl+Alt+L.
The most important part, which might resolve your first confusion: || is the logical OR in Java, meaning the ID must be a number between 100000 and 999999 and the attributes must not be empty. Or literally, if the ID is smaller than 100000 or larger than 999999 or any of the values are empty, there will be an error message and nothing will be done.
For the second part: null means that a variable is not set, so to prevent overwriting an entry you can check if it's already set, i.e. not equal to null. So the code changes the address variable until an address is found for which no data is set yet and then uses it to store the given data.
There are several potential problems in this code, among which:
several calls to the relatively slow Integer.parseInt(String) where it could be called once and stored into a variable
potential NumberFormatException if ID isn't a number (or is empty, or has some excess white spaces)
potential infinite loop if the array is full
But as it looks like some CS homework it shouldn't matter.
Thank You so much Mr David. I understand the first part where if u have a condition u can stack it on each other and from what i can understand it only works with the ||(OR) statement since using this will guarantee either a true or false ending.
while(list[address][0]!=null)
But I'm still a little confuse for part 2 of my problem. Since that line is to check the array is null meaning no value right.This is my understanding of the situation.That particular part of the code is suppose to resolve any collision if the user enters the same ID number right so shouldn't it be checking the value that's causing the collision. But the line seems to be doing is as long as a null value is detected the corresponding procedure would be implemented.

Categories

Resources