Searching a string for a time. Java - java

I am trying to get a If statement to work in java.
I have a String startTime;
I want to make it so 06:00 to 9:59 is a peak time and some other times but I just want to get one if statement working right first
i use
*if (startTime >= "06:00" && startTime <= "9:59");*
I know that strings dont really search like that but I was told by the instructor that we can use strings to accomplish the task really easy. I was also told to only use the main method not use other classes
it comes up with:
**the operator >= is undefined for the argument type(s) java.lang.String, java.lang.String**

Use String.compareTo to accomplish this.
if (startTime.compareTo("06:00")>0 && startTime.compareTo("09:59")<0) ...;

Break your string in to the hours and minutes (use String.split), then convert the two to integers (use Integer.parseInt), then comparisons are easy.

String is an object and it does not have operators like <= and >=.
You can compare two strings using equals() and equalsIgnoreCase() methods or else you can check references of string using ==.
In your case since you are comparing two strings, you will not be able to determine if one string is greater than other unless you convert it to Java Date object or to Double object or else you can also use compareTo() method.

Related

Several string inputs for one variable

Is there any other way to shorten this condition?
if (oper.equals("add") || oper.equals("Add") || oper.equals("addition") ||
oper.equals("Addition") || oper.equals("+"))
I was just wondering if there's something I can do to 'shortcut' this. The user will type a string when prompted what kind of operation is to be performed in my simple calculator program. Our professor said our program should accept whether the user enters "add", or "Add", you know, in lowercase letters or not... Or is the only way I should do it?
You can use String#equalsIgnoreCase(String) for 1st four strings: -
if (oper.equalsIgnoreCase("add") ||
oper.equalsIgnoreCase("addition") ||
oper.equals("+"))
If number of strings increases, you would be better off with a List, and use its contains method. But just for these inputs, you can follow this approach only.
Another way to approach this is to use String#matches(String) method, which takes a regex: -
if (oper.matches("add|addition|[+]")
But, you don't really need a regex for this. Specially, this method can become ugly for greater inputs. But, it's just a way for this case. So, you can choose either of them. 1st one is more clear to watch on first go.
Alternatively, you can also use enum to store operators, and pass it's instance everywhere, rather than a string. It would be more easy to work with. The enum would look like this:
public enum Operator {
ADD,
SUB,
MUL,
DIV;
}
You can enhance it to your appropriate need. Note that, since you are getting user input, you would first need to identify the appropriate enum instance based on it, and from there-on you can work on that enum instance, rather than String.
In addition to #Rohit's answer, I would like to add this.
In case of comparison of strings, if oper is null a NullPointerException could be thrown. SO its always better to write
"addition".equalsIgnoreCase(oper)
instead of
oper.equalsIgnoreCase("addition")
If aDD is considered as invalid input, you can consider following approach:
ArrayList<String> possibleInputs = new ArrayList<String>();
possibleInputs.add("Add");
possibleInputs.add("add");
possibleInputs.add("Addition");
possibleInputs.add("addition");
possibleInputs.add("+");
if(possibleInputs.contains(oper))
{
// ...
}
throw that whole bit of code inside a function called: isOperationAddition(String s){...} that returns a boolean.
So this:
if (oper.equals("add") || oper.equals("Add") || oper.equals("addition") ||
oper.equals("Addition") || oper.equals("+")){...}
Changes to this
if (isOperationAddition(operation)){...}
Then inside that method, don't use Strings as branch material for your if statements. Have a variable that defines which kind of operation it is and "Keep the barbarians (confusion/ambiguous users) out at the moat". You should not be always iterating against a list to remember what operation we are dealing with.
You can take the input, and convert in to lower case then compare.
str.toLowerCase()
then pass to your if() statement
if(str.equals("add") || str.equals("addition") || str.equals("+"))

if statement not working to filter empty names [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
If statement using == gives unexpected result
Hi I'm using this code to add elements to my ComboBox, and I do not want to add empty elements, here's the code:
public void elrendezesBetoltes(ArrayList<Elrendezes> ElrLista){
int i;
Elrendezes tmp;
model.removeAllElements();
model = new DefaultComboBoxModel(comboBoxItems);
for(i=0; i<ElrLista.size(); i++){
tmp = ElrLista.get(i);
if(tmp.getName()!="")comboBoxItems.add(tmp.getName()); //not working
addButton2(tmp.getSeatnum(),tmp.getCoord(),tmp.getFoglalt());
}
}
My problem is that the if statement is not working, it still adds empty names to my combobox. What am I doing wrong?
Always use equals method to compare Strings: -
if (tmp.getName()!="")
should be: -
if (!tmp.getName().equals(""))
or simply use this, if you want to check for empty string: -
if (!tmp.getName().isEmpty()) {
comboBoxItems.add(tmp.getName());
}
Use equals method to compare string. By using != operator, you are comparing the string instances, which is always going the be true as they(tmp.getName() and "") are not same string instances.
Change
tmp.getName()!=""
to
!"".equals(tmp.getName())
Putting "" as first string in comparison will take care of your null scenario as well i.e. it will not break if tmp.getName() is null.
Use equals():
if (!tmp.getName().equals(""))
Using == or != compares string references, not string contents. This is almost never what you want.
you have to compare Strings with "equals", then it will work
if(!tmp.getName().equals(""))comboBoxItems.add(tmp.getName())
you are comparing for identity (==, !=) but each String instance has its own identity, even when they are equal.
So you need to do !tmp.getName().equals("").
Generally it is considered best practice to start with the constant string first, because it will never be null: !"".equals(tmp.getName())
However, I would recommend to use apache commons lang StringUtils. It has a notEmpty() and notBlank() method that take care of null handling and also trimming.
PS: sometimes identity will work for Strings. but it should not be relied upon as it is caused by compiler or jvm optimization due to String immutability.
Use String#isEmpty()
if(!tmp.getName().isEmpty())
OR:
if(!tmp.getName().equals(""))
Always, check String equality with equals method. == operator only checks if two references point to the same String object.
Another alternative if not on Java 6 and isEmpty is unavailable is this:
if (tmp.getName.length()>0)
Checking for the length is supposed to be quicker than using .equals although tbh the potential gain is so small its not worth worrying too much about.

Comparing two strings in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I know it' a dumb question but why this code doesn't work.
boolean correct = "SampleText" == ((EditText)findViewById(R.id.editText1)).getText().toString();
if(correct) ((TextView)findViewById(R.id.textView1)).setText("correct!");
else ((TextView)findViewById(R.id.textView1)).setText("uncorrect!");
The point is to check if content of "editText1" is equal to "Sample Text"
In Java, two strings (and in general, two objects) must be compared using equals(), not ==. The == operator tests for identity (meaning: testing if two objects are exactly the same in memory), whereas the method equals() tests two objects for equality (meaning: testing if two objects have the same value), no matter if they're two different objects. Almost always you're interested in equality, not in identity.
To fix your code, do this:
String str = ((EditText)findViewById(R.id.editText1)).getText().toString();
boolean correct = "SampleText".equals(str);
Also notice that it's a good practice to put the string literal first in the call to equals(), in this way you're safe in case the second string is null, avoiding a possible NullPointerException.
In Java Strings have to be compared with their equals() method:
String foo = "foo";
String bar = "bar";
if (foo.equals(bar)) System.out.println("correct");
else System.out.println("incorrect");
to compare the values for two strings (for equality), you need to use equals, not == (or use equalsIgnoreCase if you do not care about case sensitivity).
Using equals will check the contents/values of the strings (as opposed to "==" which will only check if the two variables point to the same object - not the same value).
The correct way to compare 2 objects in java is using equals() method of Object class
And as String is an object in java, it should be compared in same way.
The correct way to compare a String is with,
s1.equals(s2)
So you can use this,
boolean correct = "SampleText".equals(((EditText)findViewById(R.id.editText1)).getText().toString());
((TextView)findViewById(R.id.textView1)).setText("SampleTest".equals(((EditText)findViewById(R.id.editText1)).getText().toString()) ? "correct!" : "incorrect!");
It's a bit long and theres probably a better way you could do this. The .toString() feels weird!

Android - Java if (a OR b)?

I would like to know how to express OR in Java. I always thought it was ||. But this does not work in my Android App.
So e.g here:
if (team1.getText() **"OR"?** team2.getText() == "myteam");
How can I set the OR statement?
if("myteam".equals(team1.getText()) || "myteam".equals(team2.getText()))
You cannot do something like if((foo || bar).equals(anotherString)).
A couple of this might be causing the problem. if(team1.getText()) will break, as it is not a boolean statement, so you cannot use the || operator on it.
The other problem is your method of comparing strings. Strings in java are not comparable with the == operator, because that is trying to compare the location in memory of a two String objects or literals, or a mix, and that will not return true unless they are the same instance of a String.
You have to compare strings with the equals() method on a String object or a string literal.

Most elegant isNumeric() solution for java

I'm porting a small snippet of PHP code to java right now, and I was relying on the function is_numeric($x) to determine if $x is a number or not. There doesn't seem to be an equivalent function in java, and I'm not satisfied with the current solutions I've found so far.
I'm leaning toward the regular expression solution found here: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Which method should I use and why?
Note that the PHP isNumeric() function will correctly determine that hex and scientific notation are numbers, which the regex approach you link to will not.
One option, especially if you are already using Apache Commons libraries, is to use NumberUtils.isNumber(), from Commons-Lang. It will handle the same cases that the PHP function will handle.
Have you looked into using StringUtils library?
There's a isNumeric() function which might be what you're looking for.
(Note that "" would be evaluated to true)
It's usually a bad idea to have a number in a String. If you want to use this number then parse it and use it as a numeric. You shouldn't need to "check" if it's a numeric, either you want to use it as a numeric or not.
If you need to convert it, then you can use every parser from Integer.parseInt(String) to BigDecimal(String)
If you just need to check that the content can be seen as a numeric then you can get away with regular expressions.
And don't use the parseInt if your string can contain a float.
Optionally you can use a regular expression as well.
if (theString.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")))
return true;
return false;
Did you try Integer.parseInt()? (I'm not sure of the method name, but the Integer class has a method that creates an Integer object from strings). Or if you need to handle non-integer numbers, similar methods are available for Double objects as well. If these fail, an exception is thrown.
If you need to parse very large numbers (larger than int/double), and don't need the exact value, then a simple regex based method might be sufficient.
In a strongly typed language, a generic isNumeric(String num) method is not very useful. 13214384348934918434441 is numeric, but won't fit in most types. Many of those where is does fit won't return the same value.
As Colin has noted, carrying numbers in Strings withing the application is not recommended. The isNumberic function should only be applicable for input data on interface methods. These should have a more precise definition than isNumeric. Others have provided various solutions. Regular expressions can be used to test a number of conditions at once, including String length.
Just use
if((x instanceof Number)
//if checking for parsable number also
|| (x instanceof String && x.matches("((-|\+)?[0-9]+(\.[0-9]+)?)+"))
){
...
}
//---All numeric types including BigDecimal extend Number

Categories