How can I compare a string value with string from spinner? - android-spinner

I am comparing a string value from selected string value from spinner. However, even if the string that I am testing is the same string value from spinner it always return false. I have tested different ways, simplifying the conditions and it always ends the same. The printed value in the log is the same with the string, so why does it always return false?
final Spinner spinner_familyTest = (Spinner) findViewById(R.id.spinner_family);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.family_array, R.layout.spinner_layout);
adapter.setDropDownViewResource(R.layout.spinner_layout);
spinner_familyTest.setAdapter(adapter);
// Value of familyTest from spinner as printed in the log is "Apiaceae"
familyTest = spinner_familyTest.getSelectedItem().toString();
if (familyTest == "Apiaceae") {
Log.i(TAG, "This is True!");
}
Log.i(TAG, "This is False");

I had faced the same issue some time back. The trick was to use equals() instead of ==
equals() compares string values whereas == compares string refrences
So what you need to do is:
if (familyTest.equals("Apiaceae"))
{
Log.i(TAG, "This is True!");
}

Related

Making sure every Alphabet is in a string (Kotlin)

So I have a question where I am checking if a string has every letter of the alphabet in it. I was able to check if there is alphabet in the string, but I'm not sure how to check if there is EVERY alphabet in said string. Here's the code
fun isPangram (pangram: Array<String>) : String {
var panString : String
var outcome = ""
for (i in pangram.indices){
panString = pangram[i]
if (panString.matches(".^*[a-z].*".toRegex())){
outcome = outcome.plus('1')
}
else {outcome = outcome.plus('0')}
}
return outcome
}
Any ideas are welcomed Thanks.
I think it would be easier to check if all members of the alphabet range are in each string than to use Regex:
fun isPangram(pangram: Array<String>): String =
pangram.joinToString("") { inputString ->
when {
('a'..'z').all { it in inputString.lowercase() } -> "1"
else -> "0"
}
}
Hi this is how you can make with regular expression
Kotlin Syntax
fun isStrinfContainsAllAlphabeta( input: String) {
return input.lowercase()
.replace("[^a-z]".toRegex(), "")
.replace("(.)(?=.*\\1)".toRegex(), "")
.length == 26;
}
In java:
public static boolean isStrinfContainsAllAlphabeta(String input) {
return input.toLowerCase()
.replace("[^a-z]", "")
.replace("(.)(?=.*\\1)", "")
.length() == 26;
}
the function takes only one string. The first "replaceAll" removes all the non-alphabet characters, The second one removes the duplicated character, then you check how many characters remained.
Just to bounce off Tenfour04's solution, if you write two functions (one for the pangram check, one for processing the array) I feel like you can make it a little more readable, since they're really two separate tasks. (This is partly an excuse to show you some Kotlin tricks!)
val String.isPangram get() = ('a'..'z').all { this.contains(it, ignoreCase = true) }
fun checkPangrams(strings: Array<String>) =
strings.joinToString("") { if (it.isPangram) "1" else "0" }
You could use an extension function instead of an extension property (so it.isPangram()), or just a plain function with a parameter (isPangram(it)), but you can write stuff that almost reads like English, if you want!

TextField.text is assigned with a multi-line string, but they're not equal right after the assignment

I have an Array of strings:
private var phrase:Array = ["You will be given a series of questions like this:\n2 + 2 =\n(click or press ENTER to continue)","You can use the Keyboard or Mouse\nto deliver the answer\n\"ENTER\" locks it in.\n(click or press ENTER to continue)","\nClick Here\n to start."];
I have a conditional later in the script to see if the phrase[0] is equal to the instructText.text, so I put a "test" directly after the assignment as below:
instructText.text = phrase[0];
if (instructText.text == phrase[0]) {
trace("phrase zero");
}
else {
trace("nottttttttt");
}
//OUTPUT: nottttttttt
I've tried various combinations of phrase[0] as String and String(phrase[0]), but haven't had any luck.
What am I missing?
Turns out that the text property of the TextField class converts the "Line Feed" characters (the "\n", ASCII code of 1010=A16) to the character of "Carriage Return" (the ASCII code of 1310=D16).
So, you need a LF to CR conversion (or vise-versa) to make a homogeneous comparison of what is stored in the property against what you have in the array element:
function replaceLFwithCR(s:String):String {
return s.replace(/\n/g, String.fromCharCode(13));
}
if (instructText.text == replaceCRwithLF(phrase[0])) {
trace("They are equal :)");
}
else {
trace("They are NOT equal :(");
}
// Output: They are equal :)
P.S. To get the code of a character, you may utilize the charCodeAt() method of the String class:
trace("\n".charCodeAt(0)); // 10

Comparing strings inside of two objects

I've been trying to compare the string inside of the Card() object with the other Card() objects to check for duplicates when the playing cards are dealt.
Except when printing out the compare statement i'm getting something like Card#97sd829. I made my own Equals() method for comparison of the object Card() inside of the Class but still to no avail.
I've tried using the override of the equals() object but I'm getting an error saying it needs to be inside of a superclass?
public static boolean Equals(Card a, Card b) {
String str1 = a.toString();
String str2 = b.toString();
if (str1.equals(str2))
return true;
else
return false;
}
public static boolean checkDuplicate (Card a, Card b, Card c, Card d, Card e){
int num = 5;
boolean bool = true;
if (Card.Equals(a, b)||Card.Equals(a, c)||Card.Equals(a, d)||Card.Equals(a, e)||
Card.Equals(b, c)||Card.Equals(b, d)||Card.Equals(b, e)||Card.Equals(c, d)||
Card.Equals(c, e)||Card.Equals(d, e)); num--;
if (num == 5)
bool = false;
else
bool = true;
return bool;
}
You are using the toString() method of the Object.class to get a String representation of your cards.
The default implementation of toString() contains the hash of the object. Since you have two different Card-objects the toString() method of these objects produces different output.
A better way would be to implement equals() in the Card class. Then you could check for equality with a.equals(b).
If you want advice how to implement Card.equals() you should post the source code of the Card class.

Taking a string from a user and checking it against a "Password" variable

I am trying to create a program that takes a string from a user and checks it against a "password" variable. If the password is equal it prints "valid" if not then "invalid"
Here is what I have so far, it looks correct to me, but it apparently isn't.
import java.util.*;
class WS6Q5 {
public static void main (String[] args){
Scanner in=new Scanner(System.in);
String s =" ";
int x = 123;
System.out.println("Please type in the Password");
s=in.nextLine();
if (s.length()==x){
System.out.println("Access Granted");
}
else if (s.length()!=x){
System.out.println("Invalid");
}
}
As one might expect, s.length() gives you the length, in characters, of string s. Your variable x is set to the integer (not string!) value 123. So your if-statement is seeing whether x is 123 characters long. Probably not what you want!
You probably want x to be a string. String x = "123".
You want to compare the value of x to the value of s. Look at String.equals() (http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#equals(java.lang.Object))

Is is possible to do #Unique() inside Java in XPages?

When I want a unique key for documents I'm partial to using #Unique(). I like that it's based on username and time.
Is there a way to get that from inside a Java bean?
If not, what's the best way to get a unique number in Java that would not repeat?
Thanks
This is what I use whenever I need a unique number:
String controlNumber = UUID.randomUUID().toString();
Yes you can. When you get a handle to Session call evaluate. You can evaluate any formula expressions with this method.
String ID = (String)session.evaluate("#Unique").elementAt(0);
Russell's answer is correct. But if you need a shorter unique key, you can also try this alternative:
public static String getUnique() {
String CHARLIST = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
long number=System.currentTimeMillis();
int base=CHARLIST.length();
String result="";
while (number > 0){
result = CHARLIST.charAt((int)(number%base))+result;
number = number/base;
}
return result;
}
This is basically converts the number of milliseconds from 1970 to 62-base number. You can even shorten this by getting time since 2012/12/31 or so.
What about this:
public String getUnique() {
try {
return (String) getCurrentSession().evaluate("#Unique").elementAt(0);
} catch (NotesException e) {
return "";
}
}
// retrieve handle to a Notes-Domino object in the bean class
public static Session getCurrentSession() {
FacesContext context = FacesContext.getCurrentInstance();
return (Session) context.getApplication().getVariableResolver()
.resolveVariable(context, "session");
}
It will return a familiar Unique string. Unfortunately with the signature of your server, not the current username when it runs in a browser. I the client it will work as intended.
The following is the LotusScript code I developed a long time ago as part of my .DominoFramework to reproduce the behavior of #Unique(). You should be able to convert this to Java to get a set of values similar to what you are used to.
Function unique() As String
Dim Index As Integer
Try:
On Error GoTo Catch
Randomize
Unique = ""
For Index% = 1 To 4
Unique$ = Unique$ + Chr$(CInt(Rnd(Index%)*26)+65)
Next Index%
Unique$ = Unique$ + "-"
For Index% = 6 To 11
Unique$ = Unique$ + Chr$(CInt(Rnd(Index%)*26)+65)
Next Index%
Exit Function
Catch:
Stop
DominoException.throw Me, Nothing
Exit Function
End Function

Resources