android splinting Strings - java

I I have is a server witch is sending me a String such as "False~False~False~True~False~True~False~" or something of that nature so what I have done is I did a split on that string to the "~" so my code was String[] AString = A2MCString.split("~"); with the new string array I have I went to a cheack to see if each sections was true or false using an if else statment
if (AString[0] == "True") {
Log.d("ClientActivity","Light ON");
On1.setBackgroundResource(R.drawable.selected_on);
}
else Log.d("ClientActivity","Light OFF");
however even when the server send me true in the first part of my string array the array still bounces to else saying that it is false even though it was true? Any help for my problem thanks!

When comparing strings in java you must use the equals method. In your case something like
if (AString[0].equals("True")) {
Log.d("ClientActivity","Light ON");
On1.setBackgroundResource(R.drawable.selected_on);
}
else Log.d("ClientActivity","Light OFF");
When using the == operator on objects (in java a string is an object), it is comparing if the two object references point to the same object.

Related

Java grammar questions

I am learning Android and taking the MOOC offered by Maryland University.
In one of the lectures I noticed the following line of code:
String output = (val == answer) ? "42" : "We may never know";
My guess is that this is equivalent to:
if(val == answer){
String output = "42";
}else{
String output = "We may never know";
}
Is my assumption correct?
PS: Is there anywhere besides coursera where I can take certified android classes online?
You are almost correct, it's actually like this:
String output;
if(val == answer){
output = "42";
}else{
output = "We may never know";
}
BR Erik
Your assumption is almost correct. The ternary expression would be more accurately represented as:
String output;
if (val == answer) {
output = "42";
}
else {
output = "We may never know";
}
In your original version, output is only available within the scope of the if/else blocks, since you declare it inside them. Declaring it outside the scope means you'll be able to use the value later. However, as Hariharan pointed out, using == for string comparison is a no-no in Java; you're comparing the raw objects, not the string contents. You'll want to replace your val == answer with val.equals(answer) to get a proper result.
Edit: If val and answer aren't strings, disregard the portion about using .equals(). I (and apparently everyone else who answered this question) made the bad assumption that they were, since everything else was strings. .equals() should be used for strings and any other complex object, == can be safely used for primitives.
Yes, you are correct (almost). It's called ternary operator. Your logic is good but you must take care that the variable is initialized outside of the if-else statement.
String output;
if (val == answer) {
output = "42";
} else {
output = "We may never know";
}
If the variable would be defined inside if and else blocks you would not be able to use it after the } sign because it would fall out of the scope.
Yes, you are totally right. It's so called ternary operator. take a look here and here
And a small note: it's weird to declare the same variable twice inside conditional blocks. Declare it somewhere outside .

Java if statement equality [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
How can it be possible, that If statement doesn't understand two equal things that they are the same?
Situation:
I write into txfName field only letter b and then push button "Ok".
Code:
String letter = "b";
boolean same = false;
if (letter == txfName.getText()) {
same == true;
}
After if statement program shows me that variable same is false. Why? How can it be possible?
If I write code like this:
String letter = "b";
boolean same = false;
if (letter == "b") {
same == true;
}
Then after if statement program shows me that variable same is true. I don't understand, how it can be possible.
== compares to see if two objects are the same. When you are dealing with strings they are objects, so they may not have the same reference event though they can have the same value. You want to use .equals() instead.
For more details, Strings are special in java, as there are some internal workings that have a String pool. So in some cases the == may actually seem to be working, but in other cases it may not be. The reason is the String pool tries to cache recently used Strings to reduce the memory overhead. Anyway .equals() is what you are looking for.
for your first question
String letter = "b";
boolean same = false;
if (letter.equals( txfName.getText())) {
same = true;
}
return same;
will return true if txfName.getText() returns "b"
To compare objects in java use .equals() method instead of "==" operator
Replace the following code
if (letter == txfName.getText())
to
if (letter.equals(txfName.getText()))

What will be the output from the following three code segments?

I'm currently on a self learning course for Java and have gotten completely stumped at one of the questions and was wonder if anyone can help me see sense...
Question: What will be the output from the following three code segments? Explain fully the differences.
public static void method2(){
String mystring1 = "Hello World";
String mystring2 = new String("Hello World");
if (mystring1.equals(mystring2)) {
System.out.println("M2 The 2 strings are equal");
} else {
System.out.println("M2 The 2 strings are not equal");
}
}
public static void method3(){
String mystring1 = "Hello World";
String mystring2 = "Hello World";
if (mystring1 == mystring2) {
System.out.println("M3 The 2 strings are equal");
} else {
System.out.println("M3 The 2 strings are not equal");
}
}
The answer I gave:
Method 2:
"M2 The 2 strings are equal"
It returns equal because even though they are two separate strings the (mystring1.equals(mystring2)) recognises that the two strings have the exact same value. If == was used here it return as not equal because they are two different objects.
Method 3:
"M2 The 2 strings are equal"
The 2 strings are equal because they are both pointing towards the exact same string in the pool. == was used here making it look at the two values and it recognises that they both have the exact same characters. It recognises that Hello World was already in the pool so it points myString2 towards that string.
I was pretty confident in my answer but it's wrong. Any help?
Both will return true.
1) 2 new string objects are created but use .equals which means their actual value is compared. Which is equal.
2) 1 new string object is created because they are both constant at compile time. This will result in them pointing to the same object.
This sentence might be your issue:
== was used here making it look at the two values and it recognises that they both have the exact same characters.
== checks for reference equality whereas you're describing value equality.
First two are equal, second two are not. But unless you put it into main() method there will be no output at all.
EDIT: second pair are not the same because "==" compares addresses in memory.
You're right about the first one.
However the second would return "M3 The 2 strings are not equal".
This is because == tests for reference equality and since they are two different variables, they would not equal.

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.

Alternative to substring

I have a strange problem when adding a value to a String array which is later involved in an array sort using a hash map. I have a filename XFR900a, and the XFR900 part is added to the array using the following code;
private ArrayList<String> Types = new ArrayList<String>();
...
Types.add(name.substring(0,(name.length() - 1));
System.out.println(name.substring(0,(name.length() - 1));
I even print the line which gives "XFR900", however the array sort later on behaves differently when I use the following code instead;
Types.add("XFR900");
System.out.println(name.substring(0,(name.length() - 1));
which is simply the substring part done manually, very confusing.
Are there any good alternatives to substring, as there must be some odd non ascii character in there?
Phil
UPDATE
Thanks for your comments everyone. Here is some of the code that later compares the string;
for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last == matchedArray.get(i)) {
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));
As you can see I have added a test System.out.println("DO NOT MATCH" ... and below is some the output;
DO NOT MATCH :FR99-XFR900
DO NOT MATCH :XFR900-XFR900
I only run the substring on the XFR900a filename. The problem is that for the test line to be printed last != matchedArray.get(i) however they are then the same when printed out to the display.
Phil
You should never use the == operator to compare the content of strings. == checks if it is the same object. Write last.equals(matchedArray.get(i)) instead. The equals() method checks if to object are equal, not if they are the same. In case of String it checks if the two strings consists of the same characters. This might eliminate your strange behaviour.
PS: The behaviour of == on string is a little unpredictable because the java virtual machine does some optimization. If two strings are equal it is possible that the jvm uses the same object for both. This is possible because String objects are immutable anyway. This would explain the difference in behaviour if you write down the substring manually. In the one case the jvm optimizes, in the other it doesn't.
Use .equals() rather than == because they are strings!
if (last.equals(matchedArray.get(i))) {}
Never use == operator if you wanted to check the value since operator will check the Object reference equality, use equals operator which check on the value not the reference i.e. for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last.equals(matchedArray.get(i))) { // Line edited
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));

Categories