Setting a variable to a value in if statement - java

static int findPerson(String n, int NP, Friend[] giftGivers){
int index = 0;
for (int i = 0; i < NP; i++){
if (giftGivers[i].name == n){
index = i;
}
}
return index;
}
I have this code in Java for a method to search through an array of Friends to find the index number of the person with the name input by String n. however i have found that the index number does not set to the index number it is should be. Is it because it is in the if statement?

if (giftGivers[i].name == n) is wrong, use if (giftGivers[i].name.equals(n))
BTW, there is no need to use NP. It's C-style, not necessary (actually, pretty dangerous) in Java. Instead of
for (int i = 0; i < NP; i++),
just say for (int i = 0; i < giftGivers.length; i++)

You need to use equals to compare strings not ==.
== will compare the object references rather than the actual string value.
If you don't care about case, then there is also an equals method that ignores case

(giftGivers[i].name == n){
should be
(giftGivers[i].name.equals(n)){
String/Object comparison should use .equals() instead of ==
== will check for reference equality. equals() check for object equality.

.equals() method checks for equality of two string objects, == operator checks if two refrence variables point to the same String object.
In your case you have to use .equals() method
if (giftGivers[i].name.equals(n))
refer to String API.
Note that if you wanna check if two strings are equal case insensitive use equalsIgnoreCase()

Related

Total number of vowels in a string

I am getting error saying "The type of the expression must be an array type but it resolved to String"
public class StringWord {
public static void main(String[] args) {
String s = new String("Ahmedabad");
int count = 0;
System.out.println(s.length());
for(int i = 0; i < s.length(); i++){
if(s[i].equals("A")||s[i].equals("a")||s[i].equals("e")||
s[i].equals("E")||s[i].equals("i")||s[i].equals("I")||
s[i].equals("o")||s[i].equals("O")||s[i].equals("u")||
s[i].equals("U"))
{
count++;
}
}
System.out.println("Vowels in a string: "+count);
}
}
if(s[i].equals("A")||s[i].equals("a")||s[i].equals("e")||s[i].equals("E")||s[i].equals("i")
||s[i].equals("I")||s[i].equals("o")||s[i].equals("O")||s[i].equals("u")||s[i].equals("U"))
equals method compares two strings. Here you want to compare character.
use s.charAt(i) instead of s[i] since you want to compare two characters. To get the character at the index i charAt(index) method can be used. Two compare two character == operator is used.
if(s.charAt(i)=='A'||s.charAt(i)=='E'||s.charAt(i)=='I'||s.charAt(i)=='O'||s.charAt(i)=='U')||s.charAt(i)=='a'||s.charAt(i)=='e'||s.charAt(i)=='i'||s.charAt(i)=='o'||s.charAt(i)=='u')
Your variable s is a String, but you treated it like an array by doing s[i].
You should use
s.charAt(i) // a method of String class which returns the char at the index i
instead of s[i].
Strings cannot be accessed by someString[index] (this notation is used for arrays).
Use charAt(index) instead, but note that charAt() returns a char, so you have to compare it with == not with equals() that is used for Strings.
You can also simplify this by:
if ("AaEeIiOoUu".contains(Character.toString(s.charAt(i))) )
{...}
Java String objects aren't character arrays, and you can't use array syntax with them. Instead, you need to use charAt, which returns a char, not a String like you're apparently expecting, and you would need to use == to compare primitives:
if(s.charAt(i) == 'a' || ...)
Additionally, you can use the indexOf method to dramatically simplify your if statement:
static final String VOWELS = "aeiouAEIOU";
for(int i = 0; i < s.length(); i++)
if(VOWELS.indexOf(s.charAt(i)) > -1
count++;
Yes. You are using String s here. There is no index there. Use char array from s. Or you can use s.charAt(index)
INCORRECT. PLEASE DISREGARD
You need to convert the string to an array.
s.ToCharArray();
Note: this is c# code, I don't know if it is similar to java.

how is the equality between objects done?

if we create 3 variables of int type using different declaration statements, for instance,
Integer i = 10;
Integer j = new Integer(10);
int k = 10;
and we compare them for equality, we get i == k and j == k but not i==j.
what is the reason for this?
Since i has type Integer and k has type int, the expression i == k triggers unboxing: it is equivalent to i.intValue() == k (even to the point that it would raise a NullPointerException if i were null). Similarly for j == k. But since i and j both have type Integer, no autounboxing is performed, so i == j simply checks to see if they are the same object — the same instance of Integer.
Because k is primitive and when you compare it with others you only compare its integer value.But the other two are objects. When you compare them with == operator you only check if they are the same object or not.
You should use equals() method to compare Integer objects.The following will return true in your program.
i.equals(j);

Java - If statement not catching when variable equals string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
(This may be a duplicate, I was not aware of .equals. My apologies.)
I was messing around in Java today when I decided to make a 4 character string generator. I have the program generate every possible combination of characters that I defined. This isn't for a project, I just wanted to see if this was possible. My problem lies with the string checking. I'll post the code first.
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] chars = text.toCharArray();
String name = "Mike";
String pass;
outerLoop:
for (int a = 0; a < chars.length; a ++) {
for (int b = 26; b < chars.length; b++) {
for (int c = 26; c < chars.length; c++) {
for (int d = 26; d < chars.length; d++) {
pass = chars[a]+""+chars[b]+""+chars[c]+""+chars[d];
System.out.println(pass);
if (pass == name){
System.out.print("password");
break outerLoop;
}
}
}
}
}
The nested if will check if pass is equal to Mike. If it is, then it prints password and will break the for loop.
Is pass = chars[a]... the correct way to do this? When I tested it without the if, I had it print out pass and it printed all of the combinations correctly. It did print Mike, but it did not catch in the if.
I also changed the nested for loops so they start with the lower case because the program was taking a while to run when I made minor changes.
if (pass == name){
should be
if (pass.equals(name)){
use String.equals() method to check string equality. == operator simply checks if two reference variables refer to the same object. equals() method checks if two strings are meaningfully equal.
Strings should be compared using equals()
This comes up at least once per day. There should be a "close question" option dedicated to it. Nevertheless, here goes again...
The == operator tests if the two operands are the same instance.
The .equals() method compares the values of the two operands, but only if the class has implemented this method (which String does), otherwise it behaves the same as == (which is how the Object class implements it).

If condition does not work correctly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I have written this code:
public String[] removeDuplicates(String[] input){
int i;
int j;
int dups = 0;
int array_length = input.length;
for(i=0; i < array_length; i++){
//check whether it occurs more than once
for(j=0; j < array_length; j++){
if (input[i] == input[j] && i != j){
dups++; //set duplicates boolean true
input[j] = null; //remove second occurence
} //if cond
} // for j
} // for i
System.out.println("Category contained " + dups + " duplicates.");
return input;
}
which is supposed to check whether an array of strings contains one or more duplicates. However, even when I define the array like this:
String[] temp = new String[2];
temp[0] = "a";
temp[1] = "a";
The if condition is not "triggered". Did I misunderstand how && works? In my opinion, the program should first check whether the two strings are identical (which they are...) and then whether the two indices are the same. If not, it should perform the operations.
However, the programs seems to think otherwise.
One of the most common mistakes in Java is to assume that a String is an object when its a reference to an object. When you use == you are comparing references, not their contents. This is why .equals() is required to compare their contents.
BTW you can remove duplicates with
public static String[] removeDuplicates(String[] input){
return new HashSet<String>(Arrays.asList(input)).toArray(new String[0]);
}
The == operator in Java checks if the two objects are the same, not that they are equal. Two strings may have identical content, and compare negatively for equality. You need to use equals instead:
if (i != j && input[i].equals(input[j])){
}
If null values are allowed among the input elements, you need to add a null check to your condition to avoid an exception:
if (i != j && input[i] != null && input[i].equals(input[j])){
}
Never use == to check that two objects have the same value. Use equals()
== will check their memory positions (if both objects are in fact only one), equals() is the method that will tell you if both represent the same information.
While working with Strings (and any non-primitive type), remember that == makes a comparation by reference, not by value. Use equals() instead.
if (input[i].equals(input[j]) && i != j){
dups++; //set duplicates boolean true
input[j] = null; //remove second occurence
} //if cond
As a rule of thumb, use == when you want to check if two objects are EXACTLY the same object (you can think of it as if both pointers where referencing the same address).
You should use String.equals for checking string content. The == operator just checks the object reference:
if (input[i] != null && input[i].equals(input[j]) && i != j) {

Using an IF statement to control the return statement?

public static int seqSearch(int numRecords, String[] stuName,
double[] stuGpa, String nameKey, double gpaKey)
for(int i = 0; i < numRecords; i++)
if(stuName[i] == nameKey && stuGpa[i] == gpaKey)
return i;
return -1;
So, how would I used an if statement to control this? I'm doing sequential search to find if the name is found in the array and if the gpa is in the array, then it should return the position it was found in (i). But, all it does do is return -1 and print out that none were found.
You have two separate problems here:
You should be comparing strings using the equals() method (or one of it's kin) - otherwise you are comparing whether two strings are the same reference (instance) rather than equivalent sequences of characters.
You should avoid comparing doubles using == as equality for doubles is more nuanced. Check out this paper for more information about why.
See this question about why using == for floating point comparison is a bad idea in java.
Aside from that, I would also mention that your implementation makes the assumption that both stuName and stuGpa are arrays of the same length. This could easily not be the case ... and is probably something worth asserting before you begin iterating over the arrays.
Strings must be compared with .equals in Java, not ==.
if(stuName[i].equals (nameKey) && stuGpa[i] == gpaKey)
You probably want
if (stuName[i].equals(nameKey) && stuGpa[i].equals(gpaKey))
if(stuName[i] == nameKey is unlikely to be right, you are comparing object identities not string content. Try if(stuName[i].equals(nameKey)
You are comparing two Strings.
Strings are immutable.
Please use "equalsIgnoreCase()" or "equals()" to compare Strings
See examples here
http://www.java-samples.com/showtutorial.php?tutorialid=224
An essential problem is that
stuName[i] == nameKey
Is only comparing whether the objects are the same String Object in memory.
You actually want to use nameKey.equals(stuName[i]), to compare the actual string values.
And you might want to use .equalsIgnoreCase for case insensitivity.
The following is correct for the if statement. stuName[i] is a string so compare with .equals. stuGpa[i] is a double so use ==.
if(stuName[i].equals(nameKey_ && stuGpa[i] == gpaKey)
Your problem is not the conditional if statement, but the conditional operator ==. == refers to the pointer value of the object where as the .equals method returns something computed by the object.
Like everyone has said before, switch your == to .equals in this next line:
public static int seqSearch(int numRecords, String[] stuName,
double[] stuGpa, String nameKey, double gpaKey)
for(int i = 0; i < numRecords; i++)
if(stuName[i].equals(nameKey) && stuGpa[i] == gpaKey)
return i;
return -1;
To actually answer the question about the control of the if statement...
I believe what you're doing is fine with the the multiple return statements, BUT...
I personally prefer one entry point and only one exit point for my methods. It always feels dirty to me having multiple exit points.
So, I would consider the following code instead:
public static int seqSearch(int numRecords, String[] stuName, double[] stuGpa, String nameKey, double gpaKey)
int value = -1;
for(int i = 0; i < numRecords; i++) { // Don't forget your braces, they aren't required, but wait until you add a newline and forget to add them...
if(some.boolean().equals(comparison.here())) {
value = i;
break;
}
}
return value;
}
Best of Luck.

Categories