Java will not recognize "(" and ")" strings [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Java comparison with == of two strings is false? [duplicate]
(12 answers)
Closed 9 years ago.
I am trying to interpret a string input from the user. I take in a phrase, split it into an array, and compare each value in the array to ")" as a boolean. The problem is it will read the string "( 3 + 5 )", and I know that the array that takes in the string is ["(","3","+","5",")"] and when I print out position 0 and 4 of the array, it returns "(" and ")". I know that these are type string of length 1, however, when I compare the exact same values to the "(" ")" in the code, it returns false.
Any idea what's wrong? Here's my code. The parts that I am having trouble with are the if statements.
public String buildExpression(String E){
String[] exprArr=E.split(" ");
int len=exprArr.length;
BTStacker S = new BTStacker();
String val;
for (int i=0; i<len; i++){
val=exprArr[i];
System.out.println(val);
if (val=="("){
System.out.println("2");
}
else if(val != ")"){
BSTree T=new BSTree();
BSTNode v=new BSTNode(val,null);
T.addRoot(v);
S.push(T);
}
else{
BSTree Ty = S.pop();
BSTree T=S.pop();
BSTree Tx=S.pop();
T.attach(T.root(),Tx,Ty);
S.push(T);
}
}
}

When you compare Strings in Java, you need to use .equals(), not ==, because Strings are Objects.

NEVER compare strings using ==.
Always compare using the equals method.
val.equals("(")
Note that when using "==" to compare string objects, you are not comparing it's values but it's references.

Related

Java 8, updating element in array [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have trouble with my code. I need to replace element in Array if condition is true.
Inputs are:
dashedCapital = "------";
input = "a";
capital = "Warsaw";
Code should check if capital contains input and if yes replace "-" in dashedCapital to character from input at specified position:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
String[] capitalArray = capital.split("");
String[] dashedCapitalArray = dashedCapital.split("");
String[] character = input.split("");
for(int i = 0; i < capitalArray.length; i++){
//System.out.println(i);
//System.out.println(capitalArray[i] + character[0] + dashedCapitalArray[i]);
if(capitalArray[i] == character[0]){
dashedCapitalArray[i] = character[0];
}
}
String result = Arrays.toString(dashedCapitalArray);
System.out.println(result);
return result;
}
Result is "------" but should be "-a--a-". What's going wrong?
John, thanks for your reply, it was helpful.
I edited my method so it's look like this now:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
for(int i = 0; i < capital.length(); i++){
if(capital.charAt(i).equals(input.charAt(0))) {
String new_dashed = dashedCapital.substring(0,i)+input.charAt(0)+dashedCapital.substring(i);
System.out.println(new_dashed);
}
}
return "OK:";
Now i get this error:
GetWord.java:69: error: char cannot be dereferenced
if(capital.charAt(i).equals(input.charAt(0))) {
^
1 error
I don't understand why it's wrong. I using a equals() function. I also tried "==" operator but then nothing happens. What does it mean "char cannot be dereferenced"? How I could compare single chars from string with another chars from another string?
The reason it is not working is because your if for character equality is never true. You’re comparing strings of length 1 and not characters. You can quickly fix by changing if be using the string comparing function .equals()
if(capitalArray[i].equals(character[0])){
...
}
However, you should change your code and not just use this fix. Don’t split your stings into arrays, just use the .charAt() method to get a character at a particular index.

How to use input to get a particular element in a list? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm new to Java/programming and I'm trying to write a simple program that gets an element from a list IF that element is equal to some user input. I'm using a for-loop and if-statement to achieve this but even though the user input and element matches up the programming won't print the element to screen. If someone could explain why this is not working it would be very appreciated. Cheers
public static void main(String[] args){
ArrayList<String> names = new ArrayList<String>();
String tempObject;
String findName;
names.add("John");
names.add("Ronny");
names.add("Gona");
names.add("Gina");
Scanner Input = new Scanner(System.in);
System.out.print("Search list for: ");
findName = Input.nextLine();
for (int i = 0; i < names.size(); i++){
tempObject = names.get(i);
if (tempObject == findName){
System.out.print("\n" + tempObject);
}
}
}
Here you go:
if (tempObject.equals(findName)){
System.out.print("\n" + tempObject);
}
For objects, which String is, always use method equals(), since == will compare references, not values (or what is set in equals() method - in String, it will compare the size, and then compare each char on the same place if they are equal - also, if you need, you have a method called equalsIgnoreCase - sometimes, its better to use that for user inputs).
For primitives, you will have to use ==.
There is difference between equality and identity, in your code above you used identity instead of equality, if you change your code (to use equality) as the below you will get what you need
if (tempObject.equal(findName)){
System.out.print("\n" + tempObject);
}
You should use String equals to compare two Strings for equality, not operator == which just compares the references.
Try the if statement like this:
if (tempObject.equals(findName)){...}

Why does "T" not equal "T" in this example? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm trying to write a simple hangman game in java for my college class. For some reason the if statement never returns seems to think that the two substrings being compared are equal. The two print statements show that by all rights the two should equate.
public String guessLetter(String letter)
{
String blanks = "";
String theWord="FOO";
for(int i=0; i<=theWord.length()-1; i++)
{
System.out.print(letter.substring(0,1).toUpperCase());
System.out.print(theWord.substring(i,i+1)+ "\n");
if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1)))
{
blanks = blanks + theWord.substring(i,i+1);
}
else
{
blanks = blanks + "___ ";
}
}
return blanks;
}
EDIT - As a great many people have pointed out, when comparing Strings, one must use the equals method instead of ==. I was unaware.
You are comparing a String so use "String".equals() dont use ==
use like this:
if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))
Java dont have == for string
you must use string1.equals(string2) function
if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1))) \ this is wrong for strings
When you compare strings you should use .equals or .equalsIgnorecase
if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))
ans also checkout the difference between == and .equals in java good explanation is given there.

If statement wont recognize string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have an if statement that takes a string, and if another string has the same value as that string do 1 thing, and if the variable doesnt equal that string do another thring
here is my code
if(Pos != "D"){
System.out.println("doesnt = D");
}
if (Pos == "D" ){//WHY ISNT THIS WORKING
System.out.println("it does = D");
}
It recognizes when the variable doesnt = D and prints "doesnt = d" but when the variable = D it does nothing. I dont know why.
thanks
Never compare Strings with == or != since these check to see if two String variables refer to the same object reference, and this is not what you're interested in. Instead use the equals(...) or equalsIgnoreCase(...) method to see if the two Strings have the same chars in the same order as that's what really matters here. i.e.,
Use equals to compare strings :
if ("D".equals(Pos))

Why don't strings compare as equal? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String is not equal to string?
I'm new to java and I can't figure out what's wrong with this code block.
I know the array isn't null I'm testing it elsewhere. Maybe there is a syntax problem I'm used to program in c#.
Scanner input = new Scanner(System.in);
System.out.println("Enter ID :");
String employeeId = input.nextLine();
int index = -1;
for(int i = 0 ; i < employeeCounter ; i++)
{
if(employeeId == employeeNumber[i])
{
index = i;
}
}
if(index == -1)
{
System.out.println("Invalid");
return;
}
I always get to the 'Invalid' part. Any idea why ?
Thanks in advance
employeeNumber[0] is "12345"
employeeId is "12345"
but I can,t get into the first if statement although employeeId IS equal to employeeNumber[0].
Don't compare strings with ==.
Use
if (string1.equals("other")) {
// they match
}
Compare strings like that
if(employeeId.equals(employeeNumber[i]) {
}
As others have pointed - full code will be helpful, but my guess would be this line of the code:
if(employeeId == employeeNumber[i])
You don't compare 2 strings by using ==. Use equals() or equalsIgnoreCase() instead. == only checks for object equality i.e. are employeeId and employeeNumber referencing to the same object in memory. So, for objects always use the equals() method..for Strings you can also use equalsIgnoreCase() for a case insensitive match. == should be used on primitive types like int, long etc.
When you use == with two string, it compares pointer addresses
You should use firststring.equals(secondstring) in order to compare two strings
Use equals() method to compare Strings
if(employeeId.equals(employeeNumber[i])){}
When you compare strings, use
String1.equals(String2);
This should give you the result
"==" checks whether the reference for two objects are same. But equals() method checks whether the content is same or different.

Categories