If statement constantly activating in android - java

I am working on some code that will allow the program to check if the user has entered a name and a birth day and decide if the birthday is today and play happy birthday. However while I have managed to get the program to use the correct date and play the songs the if statements do not seem to be working properly. When ever I enter the current date as the birthday the happy birthday song always starts up even when the name box is empty and it should ask for your name. This only happens when the birthday textbox and the current day match, so could anyone help me to get my if statement working correctly. Here is my if statement code.
if((btn==v) && (name.getText().toString()!="") && (bday.getText().toString()!="") && (bday.getText().toString().equals(formatdate))){
String msg1 = "Today is " + sdf.format(cdate.getTime()) + ". Happy Birthday, " + name.getText() + "!";
toast = Toast.makeText(this, msg1, Toast.LENGTH_SHORT);
toast.show();
//Context context = null;
mp.start();
//mp.stop();
response.setText(msg1);
}else if(btn==v && name.getText().toString().equals("") && bday.getText().toString()!=""){
String msg3 = "Please enter your name.";
toast = Toast.makeText(this, msg3, Toast.LENGTH_SHORT);
toast.show();
mp.stop();
response.setText(msg3);
}else if(btn==v && name.getText().toString()!="" && bday.getText().toString().equals("")){
String msg4 = "Please enter your birthday.";
toast = Toast.makeText(this, msg4, Toast.LENGTH_SHORT);
toast.show();
response.setText(msg4);
}else if(btn==v && name.getText().toString().equals("") && bday.getText().toString().equals("")){
String msg5 = "Please enter your name and birthday.";
toast = Toast.makeText(this, msg5, Toast.LENGTH_SHORT);
toast.show();
response.setText(msg5);
}else{
String msg2 = "Today is " + formatdate + ". Sorry today is not your birthday.";
toast = Toast.makeText(this, msg2, Toast.LENGTH_SHORT);
toast.show();
response.setText(msg2);
}

There are a few things that you need to change. You don't need to do this:
name.getText().toString()
You can get rid of the toString() part.
Second. Instead of doing something like this:
name.getText().toString()!=""
Change it to this:
!name.getText().equals("")
Because .equals() returns a boolean and you can't compare strings with == or != etc.
Finally, you need to make sure not to use b == v but b.equals(v)

I think the problem lies in the "!=" operator. In Java, the operator "==" and "!=" only compare if the referenced object is equal. It means the object only "==" itself. While the ".equals()" function compares the content of two objects. You should always use "equals()" function to compare the content of two objects.
use
btn.euqals(v);
!name.getText().toString().equals("");
instead.

In Java the == operator is a simple comparison of values. For
object references, the values are the references, so x == y
returns true if x and y reference the same object.
no need of toString() for getText() since it itself returns string.
change bday.getText().toString()!="" to !bday.getText().equals("")
change name.getText().toString()!="" to !name.getText().equals("")

Related

Java If Statement having multiple conditions with && operator not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
private void validate(String userName, String userPassword){
if((userName == "Admin") && (userPassword == "1234")){
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
} else{
counter --;
Info.setText(userName + " Number of Attempts Left: "+String.valueOf(counter) + " - " + userPassword);
if(counter == 0){
Login.setEnabled(false);
}
}
}
Whenever i give input as "Admin" and "1234" condition goes to else part. please help me i am beginner in this field.
string equals() method compares the two given strings based on the
data/content of the string.
Try with
if(userName.equals("Admin") && userPassword.equals("1234")){
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
} else{
counter --;
Info.setText(userName + " Number of Attempts Left: "+String.valueOf(counter) + " - " + userPassword);
if(counter == 0){
Login.setEnabled(false);
}
}
You should compare strings using equals method:
"Admin".equals(UserName)
BTW, the code above is a bit safer than
UserName.equals("Admin")
because it does not throw NullPointerException when UserName is null.
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
Therefore use .equals(), or equalsIgnoreCase() instead of == for comparing String objects.

Error: unexpected type required: variable found: value

Im trying to make this variable int stringSize to print "ok" or "not ok" depending on the if statement.
Heres what i have:
int stringSize = (n_1 + n_2 + n_3);
if (stringSize < 20){
String.valueOf(stringSize) = "ok";
}else if (stringSize > 20){
String.valueOf(stringSize) = "not ok";
}
Theres more code but its irrelevant to the question, I think. Nevertheless everything is defined except until here.
I know i cant just put it equals to the "ok" so how do i get the stringSize to print either "ok" or "not ok"?
Im a beginner, so lets be nice and i tried looking up other solutions but none were similar to my case
TY in advance
In your code, stringSize is an integer, to store a string like "ok" or "not ok", you should use a String variable. Declare a String variable and store the value in that. For example -
int stringSize = (n_1 + n_2 + n_3);
String message = null;
if (stringSize < 20){
message = "ok";
}else if (stringSize > 20){
message = "not ok";
}
Moreover, String.valueOf() returns the string representation of the parameter where you cannot assign another value. For example, String.valueOf(stringSize) will return "15" if the value of stringSize is 15.
How do i get the stringSize to print either "ok" or "not ok"?
Just put the following line wherever you want to print the message. [following the example given above]
if(message != null){
System.out.println(message);
}
String.valueOf(stringSize) is an expression, you cannot assign a value to an expression. In fact, an expression has a value. All you need is to define a variable of type String: String message = "ok";
You can't assign a value to the result of an expression, however you mentioned you want to print the value. You can do that. Like,
if (stringSize < 20){
System.out.println("ok");
} else { // <-- if it should be ok or not ok, use else.
System.out.println("not ok");
}

int cannot be converted to String in showConfirmDialog using JOptionPane

I am trying to run the following piece of code in the main Java class:
personName = JOptionPane.showInputDialog("Enter the name of the person !");
onepty.setNameOfPerson(personName);
SpeechDecision = JOptionPane.showConfirmDialog(null,
"Select Yes or No", "choose one", JOptionPane.YES_NO_OPTION);
onepty.speechCheck(speechDecision);
The following method is defined in a data definition class which I am accessing via onepty object as shown above:
public String speechCheck(String str){
if(str == "Yes" || str =="YES"||str == "Y" ||str== "y"||str=="YEs"||str=="yeS"||str=="yES"){
this.speechVar = str;
}
else {
this.speechVar = str;
}
}
But I am getting the following error after compiling using jGrasp :
error: incompatible types: int cannot be converted to String
speechDecision = JOptionPane.showConfirmDialog(null,
^
1 error
Although the error is self explanatory but since I am net to jOptionPane, I am wondering whether the button input selected by the user after clicking on Yes or No option is getting stored as integer rather than string? Do I need to modify my speechCheck method to catch Integer value?Please advise.
The variable SpeechDecision is probably String, and it should be an int since that's the returned value from showConfirmDialog, see its signature:
public static int showConfirmDialog(...)
↑
Few notes:
Follow the Java Naming Conventions
Don't compare String using ==, use equals instead
Indent your code for better world
You can do something like that :
int speechDecision = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (speechDecision == JOptionPane.YES_OPTION)
{
// Do something here
}
You have to use JOptionPane default constants
JOptionPane.YES_OPTION for YES and
JOptionPane.NO_OPTION for NO
and the type of SpeechDecision Should be integer.
So, Code will look like,
int speechDecision = JOptionPane.showConfirmDialog(null, "Select Yes No", "choose one", JOptionPane.YES_NO_OPTION);
if (speechDecision == JOptionPane.YES_OPTION){
// Do something here for yes
}
else{
// Do something here for no
}

Simple if statement stops code from working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm having a problem with a simple if statement and i'm not too sure why. I've got an edittext box and a button, when the user inputs a value into the edittext and then presses the button, whatever was input into the box is converted to string and stored in a variable, this variable is then displayed in a toast. Now this works perfectly fine as it is but I would like it to only display if a certain value is input into the editbox but when I put in an if statement to validate this, it seems to completely disgregard the if statement and does nothing. It does not cause any errors but it stops any toast from being displayed even if the correct string is input. I'm sure this is something simple but I can't seem to work it out. It would be great if anyone could work out why it does this.
Code below:
Working code when the if statement is commented out:
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.controlNum = inputTxt1.getText().toString();
// if((Global.controlNum == "1")||(Global.controlNum == "2" )){
Toast toast= Toast.makeText(SettingsScreen.this,"hello " + Global.controlNum, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, -100);
toast.show();
// }
}
});
if the if statement is brought in then it will do nothing:
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.controlNum = inputTxt1.getText().toString();
if((Global.controlNum == "1")||(Global.controlNum == "2" )){
Toast toast= Toast.makeText(SettingsScreen.this,"hello " + Global.controlNum, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, -100);
toast.show();
}
}
});
Read about How do I compare strings in Java?
So Simply change
if((Global.controlNum == "1")||(Global.controlNum == "2" ))
With
if(("1".equals(Global.controlNum))||("2".equals(Global.controlNum) ))
you should change it with:
if((Global.controlNum == "1")||(Global.controlNum == "2" ))
to
if((Global.controlNum.equals("1"))||(Global.controlNum.equals("2") ))
You should use equlas() to compare String
Global.controlNum.equlas("1")
Try replacing
if((Global.controlNum == "1")||(Global.controlNum == "2" ))
with
if((Global.controlNum.equalsIgnoreCase("1"))||(Global.controlNum.equalsIgnoreCase("2") ))
Use Global.controlNum.equals("1")
If you want to compare Strings in Java (Android) always use the method equals(String) or equalsIgnoreCase(String)

Getting date as a String from android

I made this little function:
public String getDay() {
String day = (String)android.text.format.DateFormat.format("E", new java.util.Date());
return day;
}
I know that the android.text.format.DateFormat.form("E", new java.util.Date()); Returns a CharSequence, but is there any problem regarding casting this from a sequence of char's?
I used the function like this:
String day = getDay();
if(day == "Tue") {
Toast.makeText(TaxiFaresActivity.this, day + " inside the if", Toast.LENGTH_LONG).show();
}
But it seems to me that I ever get into the function?
If I but the Toast outside, I get the following Toast
Tue
Which is right? Why doesn't the program jumps right into the if-sentence?
In java == means you are comparing addresses not content so use equals when comparing objects:
if(day.equals("Tue"))
You should compare strings using .equals() I guess?
See for instance: http://www.leepoint.net/notes-java/data/strings/12stringcomparison.html
compare Strings for equality, don't use ==. The == operator checks
to see if two objects are exactly the same object. Two strings may be
different objects, but have the same value (have exactly the same
characters in them). Use the .equals() method to compare strings for
equality. Similarly, use the .compareTo() method to test for unequal
comparisons. \
For example,
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
you can use
if(day.matches("tue"))
{
Toast.makeText(TaxiFaresActivity.this, day + " inside the if", Toast.LENGTH_LONG).show();
}
Or You can Use
if(day.contentEquals("tue"))
{
Toast.makeText(TaxiFaresActivity.this, day + " inside the if", Toast.LENGTH_LONG).show();
}
Try this
These functions are very accurate for matching string.

Categories

Resources