I have a string
number="(1234)5678";
But the if block is not executed:
if("(".equals(number.charAt(0)))
{
System.out.println("IFFF");
}
else
{
System.out.println("OUT");
}
How do I change the boolean expression to execute the if block?
charAt() returns a char. Comparing char and String with .equals() will always return false.
You'll need
if('(' == number.charAt(0))
That is because charAt(..) returns char not String. And one of if-clauses in equals in String class is:
if (anObject instanceof String) {
...
}
you can try following code:
if(number.startsWith("(", 0))
{
System.out.println("IFFF");
}
else
{
System.out.println("OUT");
}
Or you can put: if(number.charAt(0)=='(')
The charAt() function always returns char..equals() is used for comparing strings.
Characters are primitives, you can compare them with the "==" operator.
String number="(1234)5678";
if('(' == number.charAt(0))
{
System.out.println("IFFF");
}
else
{
System.out.println("OUT");
}
Related
So I am working on a project in java and I have just a quick question.
I have a method that is receiving a string and I want to strip out the spaces and check that is is not empty. So far I have the below in place however it doesn't seem to be working properly.
public static Boolean isValid(String s) {
s.replace(" ", "");
if (s == ""){
return false;
}
else {
return true;
}
}
Any help would be appreciated :)
Ta
You can try with this:
public static Boolean isValid(String s) {
return (!s.trim().isEmpty());
}
First you have forgot the assignment for s.replace(" ",""). Store that in a variable, e.g.
x = s.replace(" ","");
For string comparison use .equals() method instead of ==
You can use the following code as well :
newString=myString.replaceAll("\\s+","");
This removes one or more spaces in between Strings as well as leading and trailing whitespaces
Use : myString.trim() to remove only leading and trailing whitespaces
and then newString.isEmpty()
You should use .equals() to compare Strings
When you're comparing strings, use .equals().
Its only in artihmetic expressions you use the == sign
TO check whether your string is empty use the .isEmpty() function
You forgot the assignment:
s = s.replace(" ", "");
EDIT:
for the comments stating that == is not working. I wanted to say that it does work for Java 7
replaceAll() method supports regular expressions as well as isEmpty() is already there in String class so we can reuse it and is safer to use here.
simply use like this:
public static Boolean isValid(String s) {
s = s.replaceAll("\\s", "");
if (s.isEmpty()) {
return false;
}
else {
return true;
}
}
Difference between equals and == incase of String comparison is well explained in the thread
value of s.replace() should be assigned to itself or some other variable.
I try to compare iBeacon.getProximityUuid() with the custom string, but it can't work.
I'm very sure the first char is "a", but the result always return false!
I use the RadiusNetwork's iBeacon library.
String tempstr = iBeacon.getProximityUuid().substring(0, 1);
if (tempstr == "a") {
return true;
}
else {
return false;
}
You must change Change if (tempstr == "a") to if (tempstr.equals("a")). In Java, the == operator is used for object equality. Because the two objects aren't the same instance, tempstr == "a" always returns false. Using the .equals method actually compares the strings.
Doing some beginner problems for Java:
Given two strings, append them together (known as "concatenation") and return the result.
However, if the concatenation creates a double-char, then omit one of the chars, so "abc" and "cat" yields "abcat".
My code:
public static String conCat(String a, String b) {
//abc (c) == cat (c)
if (a.substring(a.length()-1,a.length()) == b.substring(0,1)) {
//return (ab) + (cat)
return a.substring(0,a.length()-2) + b;
//cat (c) == abc (c)
} else if(b.substring(0,1) == a.substring(a.length()-1,a.length())) {
//return (abc) + (at)
return a + b.substring(2,b.length());
} else if (a.equals("") || b.equals("")) {
return a + b;
}
}
I don't understand why Eclipse can't recognise the String returns.
First of all, you are comparing Strings with ==, which compares them by reference. This means that equal Strings might not return true. To avoid this problem, always use .equals() to compare Strings.
Second, keep in mind that your if statements are checked in the order specified. Since you want to check for empty strings first, you should put that one on top.
Third, you have to return something on all codepaths. If all of the if statements are false, you don't return anything. If you add else return a + b; you should get the desired behavior.
Furthermore, I suggest using a slightly different approach:
public static String conCat(String a, String b) {
//If either String is empty, we want to return the other.
if (a.isEmpty()) return b;
else if (b.isEmpty()) return a;
else {
//If the last character of a is the same as the first character of b:
//Since chars are primitives, you can (only) compare them with ==
if (a.charAt(a.length()-1) == b.charAt(0))
return a + b.subString(1);
//Otherwise, just concatenate them.
else
return a + b;
}
}
Note that you can omit the else blocks, since return will end the execution of the method there, so this will also work:
public static String conCat(String a, String b) {
if (a.isEmpty()) return b;
if (b.isEmpty()) return a;
if (a.charAt(a.length()-1) == b.charAt(0)) return a + b.subString(1);
return a + b;
}
actually, it can. but all your return statements are depending on a condition, so there 'll be cases for which you haven't provided a return statement.
in those cases, the method won't return anything, even while it should return a String.
add:
return "";
or
return null;
to the end of your method and try again.
I am trying to make a script that compares the user input with another string. The problem is with my if statement. I don't get errors but it always returns the result that is in the "else" statement. Here is the code:
String [] lessons_titles = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","30","40","50","60","70","80","90"};
final TextView dan_view = (TextView)findViewById(R.id.DanText);
final int position = getIntent().getExtras().getInt("position");
final String title = lessons_titles[position];
check_b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textField = check_text.getText().toString();
if (textField == title){
dan_view.setTextColor(Color.GREEN);
}
else {
dan_view.setTextColor(Color.RED);
}
}
});
Use equals() method instead of == operator when you compare String. In case of String, two string will be equal if their reference are same and to find out that both of them referencing to the same point, you have to use equals() method. == operator can only compare primitive type value but instance of String is object.
So, your condition should be as follows...
if (textField.equals(title)){
dan_view.setTextColor(Color.GREEN);
} else {
dan_view.setTextColor(Color.RED);
}
== is for testing whether two strings are the same object; - reference equality.
You want to check the value so should use .equals()
Take a look at:
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
for further clarification.
Your error is here:
if (textField == title){ //<--
textField is a string, you need to check string equality using .equals(), e.g.
if (textField.equals(title)){ //<--
use this
if (textField.compareTo(title) == 0)
{
dan_view.setTextColor(Color.GREEN);
}
else {
dan_view.setTextColor(Color.RED);
}
"textField == title" Using == will check that they are the exact same, not just value wise but also stored in the same memory location.
Instead try using
if (textField.equals(title)){
A good example is shown here http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
I was trying this code writing exercise and I am so lost!
The exercise is:
Complete the method which takes two Strings and one boolean as input. If the boolean is true, this method compares the first two Strings, ignoring case considerations (uppercase/lowercase). Two Strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two Strings are equal ignoring case.
If the boolean is false, this method should compare two Strings and return true if the first String represents the same sequence of characters as the second String, otherwise false.
Note: compareTwoStrings("HELLO", "", false) should return false.
And here is my attempt:
public boolean compareTwoStrings (String a, String b, boolean isIgnoreCase)
{
if (a.equalsIgnoreCase(b)) {
return (isIgnoreCase==true);
}
else if (a.equals(b)) {
return (isIgnoreCase==false);
}
}
It doesn't even compile, but even if it did, I'm sure it wouldn't work.
You're doing it backwards. The subject says: if the boolean is true, then do this, else, then do that. So you should program it the same way:
if (isIgnoreCase) {
return ...
}
else {
return ...
}
The rest is left as an exercise. You should be able to figure it out by yourself.
I think the requested solution is the following method:
public boolean compareTwoStrings(String a, String b, boolean isIgnoreCase)
{
if (isIgnoreCase)
{
return a.equalsIgnoreCase(b);
}
return a.equals(b);
}
Your method das not compile because the Java compiler supposes that unter some circumstances both if conditions evalutes to false. Because of that the compiler can not ensure that at least one return statement is reachable.
This could be the solution for your problem:
public boolean compareTwoStrings (String a, String b, boolean isIgnoreCase){
if (isIgnoreCase)
return (a.toLowerCase()).equals(b.toLowerCase());
else
return a.equals(b);
}
I think this is what you are looking for.
public static void myMethod(String str, String str2, boolean bool) {
if (bool) {
str = str.toLowerCase();
str2 = str2.toLowerCase();
if (str.equals(str2))
System.out.println("strings equal");
}
else {
System.out.println("false condition");
}
}