Getting date as a String from android - java

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.

Related

Comparing two strings doesn’t work [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am a beginner in android studio. I am working on a quiz app . The app should check for two strings to be compared and give the correct answer. But comparing the two strings (even though if they are same) is not giving the correct output. Instead it is directly going to the final return statement in the code. Here’s the code:
// ...
EditText Answer1 = (EditText) findViewById(R.id.answer1);
String ans = Answer1.getText().toString();
Log.v("MainActivity", "City name :" + ans);
String answer= String.valueOf(Answer1);
// ...
public String YourAnswers(String ans, boolean isDT, boolean isHC, boolean isBO,String answer) {
String Message = "1.:You answered \n"+ans+ "\n" +ques1(answer);
Message = Message + " \n 2.: \n" +question2(isDT,isHC,isBO) ;
return Message;
}
public String ques1(String answer) {
if (answer == "Jefferson City"){//||ans=="Jeff City"||ans=="Jeffcity"||ans=="Jeffersoncity"){
return "correct";
}
else if(answer =="Jeff City") {
return "correct.";
}
else if(answer =="Jeffcity"){
return "correct..";
}
else if(answer.equals("Jeffersoncity")){
return "correct.....";
}
return "Sorry,but the correct ans is Jefferson City";
}
When it enters into ques1(), it is directly going to the last statement i.e. return "Sorry,but the correct ans is Jefferson City";. When I enter the correct answer too it is returning the above mentioned line.
Any ideas as to why this might be happening?
"==" is not the correct way to compare contents of a String in java.
use string1.equals(string2)
Use .equals() throughout instead of ==.
However try this code to allow for any capitalization of answer using toLowerCase():
import java.util.Arrays;
...
...
String[] answers = {"jefferson city","jeff city", "jeffcity", "jeffersoncity"};
if(Arrays.asList(answers).contains(answer.toLowerCase())) {
return "Correct";
} else {
return "Sorry,but the correct ans is Jefferson City";
}
Background
There are two common methods used in order to compare two strings in Java. In your example, rather than making use of one of them, you’re using == which is an equality operator—these, you can’t use to check for equality on Strings.
The first method you may use is equals, located on the String. This will check and see if all characters contained by the String are exactly the same—that is, it also makes sure the String you’re giving it has the same letter case as the one you’re comparing it to.
Here’s an example:
"Hello, world!".equals("Hello, world!"); // ‘equals’ returns true
"Hello, world!".equalsIgnoreCase("hello, world!"); // ‘equals’ returns false
The second method you may use is equalsIgnoreCase, also located on the String. This will return true if the Strings compared are the same, but don’t give into account if they’re of different cases—it doesn’t care.
Let’s repeat the previous example and see what happens:
"Hello, world!".equals("Hello, world!"); // ‘equals’ returns true
"Hello, world!".equalsIgnoreCase("hello, world!"); // ‘equals’ returns true
See how both returned true this time around?
Solution
With all this in mind, we can go ahead and fix your code up:
public String ques1(String answer)
{
if (answer.equals("Jefferson City"))
{
return "correct";
}
else if(answer.equals("Jeff City"))
{
return "correct.";
}
else if(answer.equals("Jeffcity"))
{
return "correct..";
}
else if(answer.equals("Jeffersoncity"))
{
return "correct.....";
}
return "Sorry,but the correct ans is Jefferson City";
}
That’s going to work just great!
Moreover
That I put { on new lines doesn’t affect the outcome of your program. There are however good reasons as to why you’d want to put them on separate lines. The reason I’m writing this is because I’m highly fond of bringing up the debate all over again—making people mad.
Use .equalsIgnoreCase on Strings if not case sensitive. Also to avoid nullpointer exception use the following syntax
"Jeff City".equals(stringVar);

Problems with String Input [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So, for some reason I'm having problems just USING a string input.
I don't know why. Maybe it's some incredibly stupid thing everyone knows, but I don't.
Here's the non-functioning code:
import javax.swing.*;
public class Thing {
public static void main(String[] args) {
String input;
JOptionPane.showMessageDialog(null,"Welcome to the test...");
input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
String i = input;
if(i == "Yes") {
tutorial();
} else if(input=="'Yes'") {
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
} else {
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}
}
Yes, I actually do have a tutorial method somewhere else, and it works fine.
The main problem is that if I enter 'Yes' or Yes, it still goes to the final else.
I only put in the
String i = input;
and changed it from
if(input == "Yes") {
because it didn't work then, either.
So what am I doing wrong?
Don't use the == operator to compare Strings, use equals() instead, as thoroughly explained here, here, here, here or any of the numerous duplicates.
if ("Yes".equals(input))
Or even
if ("yes".equalsIgnoreCase(input))
Notice that the operation is invoked on the "yes" literal to avoid a possible NullPointerException in the case input was null and the operation was invoked on it (Yoda condition).
From the Java Language Specification, Chapter 15 - Expressions, section 21 - Equality Operators:
15.21.3. Reference Equality Operators == and !=
While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters (§3.10.5). The contents of two strings s and t can be tested for equality by the method invocation s.equals(t).
As mentioned, the problem is that you are comparing this String using the == comparator, not the .equals() method.
If you are running on Java 7, my advice, for a cleaner solution, would be also to wrap this in a switch statement:
JOptionPane.showMessageDialog(null,"Welcome to the test...");
String input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
switch (input) {
case "Yes":
tutorial();
break;
case "'Yes'":
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
break;
default:
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}

How do I link a user input argument with a string?

So, I'm rather new to Java and I just starting a project, but I ran into some issues.
My question is... How do I link a user input (argument) with a String?
I have already defined a few Strings earlier on in my code, but in this line I want it to match up and check from the String which matches the argument and check if it contains something:
if (!cs.hasPermission("foo." + args[0]) && [CODE HERE] ){
I want [CODE HERE] to check If args[0] (user input) matches a String, if it does then check if it matches some text.
Java has a .equals() method which can be used to compare two Strings. It can used to compare two variables which hold references to String objects or to compare String literals
if( args[0].equals(someString) ) { // compare args[0] to another String variable
}
if( "someText".equals(args[0]) ) { // compare args[0] to a String literal
}
Reading through the String documentation will also be very useful to you starting out.
This is String equals api, so it should look something like:
if (!cs.hasPermission("foo." + args[0]) && args[0].equals(string){
//code
}
You can easily do it with the equals() method. But you should also check that args[0] is set.
if (args.length > 0) {
if (!cs.hasPermission("foo." + args[0]) && "StringToCompare".equals(args[0])) {
// do something
}
} else {
// handle error
}

Can't break the while loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
public void play () {
int anInteger;
//guess return code
int code;
while (true) {
String input=null;
input = JOptionPane.showInputDialog("Please enter an integer");
if (input == "-1") {
//JOptionPane.showMessageDialog(null, input);
System.exit(0);
break;
} else {
if (input==null) {
System.exit(0);
} else if (input.isEmpty()) {
continue;
} else {
anInteger = Integer.parseInt(input);
code = this.oneGuess (anInteger);
//JOptionPane.showMessageDialog(null, anInteger);
}
}
}
}
I want, if the user enter -1, show the program will not prompt the message box any more. Above is the code I have come up with, so far. Why it doesn't work?
String comparisons does NOT work with "==" operator, use "String.equals(Object)" function
input.equals("-1");
Better way would be
"-1".equals(input);
as it also takes care of null input
You are comparing strings, which are objects, with the == operator, which checks whether two object references refer to the same object instance. Instead you should use the equals method for comparing them.
There is a difference between comparing with == and equals. The first compares pointers, the latter contents. That is probably your issue.
You compare Strings with ==, which creates a problem. You can have many different String-Objects which all show "-1". The == tests, if you have exactly the same object on the left and right side. You want to know, if the objects on the left and right sie have an equal content.
Better try
input.equalsIgnoreCase("-1");
EDIT: To answer the comment: input.equalsIgnoreCase("-1") is the same as input.equals("-1") in the case of "-1" as there are no uppercase/lowercase letters in "-1". However, I prefer equalsIgnoreCase in the case of Strings, because it is defined on String, rather than on Object. Still, as the equals-definition is overridden for the String class, it works too in this example and "ignoreCase" is not needed.

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