Check string for specific number [Java] [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm trying to check a string for a specific number but it doesn't seem to find it.
string = sc.next();
if(string != "-1")
return 0;
So when I enter -1 into the input, it just continues on without breaking the program. Am I doing something wrong here?

Instead of != you need to use the operator NOT ! and the method equals
So
string = sc.next();
if (!string.equals("-1"))
return 0;
Remember infact that the operators == (or !=) check for same (or not same) object. Instead equals method check that the internal value of the string is the same of the parameter.

If you are expecting a number I would read a number.
int num = sc.nextInt();
if (num != -1) return 0;
BTW: When you use == or != for String it compares only the references, not the contents of the Strings.

Related

How do you check if a string is not equal to an object? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I ave a code where I want to use != sign. But since I am using String, How do I not equals Sign. Hers is my code. So I want all this statement not to equal to each other so it can print Tie Game.
if (Array[0] == Array[currentPlayer] && Array [1] ==
Array[currentPlayer] && !Array [2] == Array[currentPlayer])
The above code is when everything equals to each other. But I want this statements not to equal each other.
Keep in mind that I have not used Int or Char, I am using String.
For string inequality, negate a call to the equals method using the !:
String x = "ABC";
String y = "XYZ";
if(!x.equals(y)) {
//do stuff
}
! can be used to negate ANY boolean expression, and String.equals returns a boolean.
You can do something like:
if (!Array[0].equals(Array[currentPlayer]) && !Array[1].equals(Array[currentPlayer])
&& Array[2].equals(Array[currentPlayer]))
Use equals() if you want case sensitive match meaning it will look at case of string as well when matching.
If you want case insensitive matching you can use equalsIgnoreCase() method in place of equals()

'If' Statement Failing Check Involving String Array [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to create a program in Java which allows the user to pick from a list of coffees contained in a String array and continues on, but it fails the check and prints out the else statement.
Here is the relevant code:
Scanner scan = new Scanner(System.in);
String[] flavors = {"Black", "French Vanilla", "Hazelnut", "Mango", "Cherokee", "anarcho-syndicalism", "Otis" };
...
System.out.println("Today we have " + Arrays.toString(flavors));
System.out.println("Please enter the name of the coffee you would like exactly as shown above: ");
String coffee = scan.next();
...
for (int i = 0; i < flavors.length; i++) {
if (coffee == flavors[i]) {
String selection = flavors[i];
Though not shown here, I believe everything's properly formatted later on in the program. Any ideas?
In general, when comparing objects for equality in java, use .equals(). Use == for comparing primitives. In java, Strings are objects.
change:
if (coffee == flavors[i]) {
to:
if (coffee.equals(flavors[i])) {
When comparing objects with ==, they will only be equal if they are in fact the same instance.

Get String from command line → split string → if/else if statement returning else statement for no reason [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
(Sorry for the weird title, but I can't figure out what actually the problem is)
The following code should get a String from the command line first (which works), then the input is being splitted (works perfectly, too; I checked by printing both Strings before the if/else as you can see in the part I commented out again) and then it should check what the first part of the splitted String is. And for example if it equals "tweet" it should procedure with the Tweet method.
But somehow it doesn't get that right. It always executes the else statement...
Scanner sc = new Scanner(System.in);
System.out.print("> ");
String input = sc.nextLine();
String[] splitString = input.split(" ");
if(splitString.length != 2){ throw new IllegalArgumentException(); }
String command = splitString[0];
String value = splitString[1];
/*System.out.print(command);
System.out.print(value);*/
if(command == "tweet") { Tweet(value); }
else if(command == "help") { ShowHelp(); }
else { System.out.println("Command "+command+" not found."); }
I tried entering "tweet asdf", but it returns
> tweet asdf
Command tweet not found.
What did I do wrong? I'm confused D:
Use the .equals method instead of ==.
== compares the references. .equals will compare the actual content of the two strings.
When comparing strings, you will almost always want to use .equals not == as usually you are wanting to compare content, not reference.
You're using == to compare two objects. This compares their references. Use if(command.equals("tweet")) instead to compare by values.
Due to string interning depending on the JVM and implementation(official classpath, GNU classpath, etc) your approach may operate properly hit-or-miss.

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