How does the .split() method work in java? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am using Java and have been trying to split my string input into 3 parts. For example, my input will be "AND 1 1", and I am expecting it to go into my if-loop where the condition is parts[0] == "AND". But this is not the case, and I am not sure why.
My code is listed below
Scanner stringInput = new Scanner(System.in);
String input = stringInput.next();
System.out.printf("%s\n", input);
String[] parts = input.split(" ");
if (parts[0] == "AND") {
if (parts[1] == parts[2] && parts[1] == "1")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
else {
if (parts[1] == "1" || parts[2] == "0")
System.out.printf("1\n");
else
System.out.printf("0\n");
}

In Java you can not be sure that the string is the object you think it is. For this reason, you should not use == to compare objects, but use the equals function.
if (parts[0] == "AND")
should be
if (parts[0].equals("AND"))
Strings are immutable, so the functions will always return new strings, when they have to do something on them. For this reason, using == will only work in some particular cases, but never when you process them.

You are using stringInput.next() which will not read spaces. So that is the problem.
Use stringInput.nextLine() instead of stringInput.next()
String input=stringInput.nextLine(); is correct when you are working with text that contains space.
Here is the edited code.
Scanner stringInput = new Scanner(System.in);
String input = stringInput.nextLine();
System.out.printf("%s\n", input);
String[] parts = input.split(" ");
if (parts[0] == "AND") {
if (parts[1] == parts[2] && parts[1] == "1")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
else {
if (parts[1] == "1" || parts[2] == "0")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
You probably might have got an ArrayIndexOutOfBoundsException

You are using the String.split() method in correct way. The parts[0] also contains the desired "AND" after using the method.
But the problem is you are checking equality of two strings using "==" instead of equals method. When you use == then it checks whether they are same reference of string while the equals method check the values of the string.
So your checking should be something like this
if (parts[0].equals("AND"))

Use
parts[0].equals("AND") to check equality of `String`

Just to complete the Devolus answers (I can't put comments in comments yet U_U)
== compares the references, it means that is only true if two variables are pointing to the same object
e.g.
Object a = new Car()
Object b = a
Object c = new Car()
(a == b) //true
(a == c) //false
a.equals(b) //true
a.equals(c) //true

Try this piece of code:
if (parts[0].toString().equals("AND")){
if (parts[1].equals(parts[2]) && parts[1].equals("1"))
System.out.printf("1\n");
else
System.out.printf("0\n");
}else {
if (parts[1].equals("1") || parts[2].equals("0"))
System.out.printf("1\n");
else
System.out.printf("0\n");
}

There are several issues:
as JavaTechnical pointed out, you should use stringInput.nextLine() vs stringInput.next()
as everyone pointed out, use .equals() vs ==, here's a thread explaining why: Java String.equals versus ==
test against a known vs an unknown, reorder your test like so "AND".equals(part[0]) should shield you from null pointer

Try using .substring(), for example:
String a = "AND 1 1"
b = a.substring(1,3)
c = a.substring(4,5)
System.out.println(b)
System.out.println(c)
Would print "AND" then "1"

Related

My jsp page only executes the else statement [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have the following login codes.
if (uname == "Abigail" && password=="Abby14"){
response.sendRedirect("http://localhost:8080/Practical_4/member.jsp");
}
else {
response.sendRedirect("http://localhost:8080/Practical_4/index.html");
}
I realized that my jsp page treats the if-statement as if it's an else statement, and only executes the else-statement.
What you do is comparing addresses where strings are stored and not the strings them selfs in some case java will store same string in same address but you cannot count on that.Here is a code example that should explain the issue
public static void main(String... args) {
String a = "a";
String b = new String("a");
String c = "a";
System.out.println(a==b); // false
System.out.println(a==c); //true
System.out.println(a.equals(b)); // true
}
So the buttom line always use equals insterad of ==
Use equals for string comparison.
if (uname.equals("Abigail") && password.equals("Abby14")){
response.sendRedirect("http://localhost:8080/Practical_4/member.jsp");
}
else {
response.sendRedirect("http://localhost:8080/Practical_4/index.html");
}
Hope this helps.
change to use equals and change to order to prevent null pointer
if ("Abigail".equals(uname) && "Abby14".equals(password)) {

Spinner selection not passing into "if" statement [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
What is the difference between == and equals() in Java?
(26 answers)
Closed 8 years ago.
I have the following code:
public void convert()
{
String val = (String) spinner1.getItemAtPosition(spinner1.getSelectedItemPosition());
System.out.println(spinner1.getItemAtPosition(spinner1.getSelectedItemPosition()));
System.out.println(val);
if(val == "mm" || val == "cm" || val == "m" || val == "km")
{
System.out.println("got into if statements");
initiateLengthConvert();
}
System.out.println("never got it");
}
Now when the first to print statements print out, if I selected "mm", then it prints out:
mm
mm
never got it
Why won't it pass into the if statement? "val" and the possibilities match up, so it doesn't make any sense to me.
Use .equals to compare strings instead of ==.
if(val.equals("mm") || val.equals("cm") || val.equals("m") || val.equals("km"))
Read
What is the difference between == vs equals() in Java?
Also instead of System.out.println("..."); use Log
Try this..
== always just compares two references. String you should use .equals("")
if(val.equals("mm") || val.equals("cm") || val.equals("m") || val.equals("km"))
{
System.out.println("got into if statements");
initiateLengthConvert();
}

Java if or statement not working as expected [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
The or statement in the first line of my if statement is not working as i would expect it to, any suggestions?
if(answer == "deposit" || "Deposit"){
System.out.println("How much would you like to deposit?");
final int deposit = console.readInt();
account.deposit(deposit);
System.out.println( "This leaves you with $" + formatter.format(account.getBalance()) + " in your account");
}else if(answer == "Check Balance"){
System.out.println( "You have $" + formatter.format(account.getBalance()) + " in your account");
}else if(answer == "Withdraw"){
System.out.println("How much would you like to take out?");
final int with = console.readInt();
account.withdraw(with);
System.out.println( "This leaves you with $" + formatter.format(account.getBalance()) + " in your account");
}else{
System.out.println("You didn't enter a correct term, please try again.");
}
First, logical-OR conditions don't work this way in Java like they do in English. You must write it out explicitly. Second, don't use == to compare String values. Use equals() for all String value comparisons.
if ("deposit".equals(answer) || "Deposit".equals(answer))
Or you can use equalsIgnoreCase().
if ("deposit".equalsIgnoreCase(answer))
Use the method 'equals' for string comparison. E.g. answer.equals("deposit").
Use if (answer.equals("deposit") || answer.equals("Deposit")) {
and }else if(answer.equals("Check Balance")){
Testing if strings are equal in Java should not be done with ==, but with:
if ( answer.equals("Check Balance") )
With == you compare pointers of String objects, but answer and "Check Balance" are different object - second one is created during test so even if they have equal value, they are not identical. equals check only object's content.
For String you need to use String.equals method
if("deposit".equals(answer)){
Change
if(answer == "deposit" || "Deposit"){
as
if(answer.equalsIgnoreCase("deposit")){
or
if (answer.equals("deposit") || answer.equals("Deposit")) {
Reason
equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects!. That means, the contents of the objects. Whereas the == operator is expected to check the actual object instances are same or not.
Example
Consider two different reference variables str1 and str2
str1 = new String("abc");
str2 = new String("abc");
if you use the equals()
System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as TRUE
if you use ==
System.out.println((str1==str2)?"TRUE":"FALSE");
Now you will get the FALSE as output because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() everytime a new object is created.

Cant get JOptionPane string input to match a string value [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am relatively new to coding in general and have run into an issue, I've looked everywhere for help but I cant find this issue. It would be greatly appreciated if someone could tell me why the string "s" doesn't ever equal the string "temp" even if I type the correct number in.
String s = null;
do{
s = (String) JOptionPane.showInputDialog(null, "Select a card to check for (Jacks = 11, Queens = 12, Kings = 13)", "Player's Turn", JOptionPane.PLAIN_MESSAGE, null, null, "Pick a card");
System.out.println(s);
for(int x = 0; x < PlayerCards.size(); x++){
String temp = PlayerCards.get(x).getFace();
if(s == temp){
playerhas = true;
}
}
if(s == null || playerhas != true){
JOptionPane.showMessageDialog(null, "Please pick a card you have.", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}while(s == null || playerhas != true);
Strings work like objects in Java.
If you do stringA == stringB this will always return false since stringA and stringB are different objects.
Comparing strings needs to be done using stringA.equals(stringB) and this should return true (if the values match).
Chris 7 you're right that strings are objects but new compilers do some optimizations on those strings and it could happen that stringA == stringB are equal but it's not promised. So you should always use the string comparison functions (String.equals or String.equalsIgnoreCase).
By the way you can optimize your code. Use functions that implement only one feature and not more... e.g. externalize your function that checks if one has the card or not:
boolean playerHas(String s) { for (PlayerCard card : playerCards) { ... } return false; }
The
==
operator compares objects, while the
.equals
function compares object values.
String foo = "loremipsum";
String bar = "loremipsum";
System.out.println(foo == bar);
System.out.println(foo.equals(bar));
this ==compare bits, it works with primitive variable because when you declare a primitive variable it saves its value in bits, but when you declare a reference variable it only works if two reference are the same.
See this example:
String object1 = new String("hola");
String object2 = object1;
System.out.print(object1==object2);
This will return true because object2 have the same bits that point to the same object on heap, because they were copied when i said:object2 = object1
So if you want to compare objects by value instead by reference you have to use: equals() method.

Java .getText vs. Hard Coded String not returning the same results

I am completely stumped with this one . . .
If I call the function below with the following:
Search(SearchTextField.getText()); // (Fiberglass was entered)
Search("Fiberglass"); // hardcoded
I get the following results:
Fiberglass 10 Not Here
Fiberglass 10 String found!
Same String is passed with the same length, different results. How can this be?
Yes I've trimmed it on both sides of the == with no luck.
I am loosing my mind, any help would be appreciated.
Test[] array = new Test[3];
array[0] = new RowBoat("Wood", "Oars", 10);
array[1] = new PowerBoat("Fiberglass", "Outboard", 35);
array[2] = new SailBoat("Composite", "Sail", 40);
public void Search(String searchString) {
boolean found = false;
System.out.print(searchString + " " + searchString.length() + " ");
for (int i = 0; i < array.length; i++) {
if (searchString == array[i].getBoatMaterial()) {
found = true;
break;
}
}
if (found) {
System.out.println("String found!");
} else {
System.out.println("Not Here");
}
}
Use the .equals() method when you're comparing Strings. Do not use ==
equals() will compare the actual String content, no matter where the String resides in memory.
if (searchString.equals(array[i].getBoatMaterial())) {
Since String variables are references in Java, when you code
if (searchString == array[i].getBoatMaterial()) {
What you are actually doing is comparing two pointers. It just so happens that when you hardcode the same string in multiple places in your program the compiler reduces it to one instance (since Strings are immutable) and reuses it. This is why using a hardcoded value succeeds, since both pointers point to the same value. However, when the search string is not the same hardcoded "Fiberglass", the two strings are at different locations and the comparison fails. To compare two strings use the String.equals(String) method instead.
Use the String.equals(String other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal.

Categories

Resources