I didn't know how to explain the question but hopefully this will make you understand
I know this code does not work
a = "hello";
if (a.equals("hello" || "greetings")){
//Execute code
}
Is there a simple way to do this without an error
I could do this but this means that i will need to repeat codes on both
a = "hello";
if (a.equals("hello")){
//Do code
}
if (a.equals("greetings")){
//Execute code
}
This is my current code but its not what i want it to do.
What i want it to do is if for example topic = "Whats the date"; i want it to execute the code because it contains date, I cant find a way to check if it contains date and so the || works
scanner = new Scanner(System.in);
String topic = scanner.nextLine();
topic = topic.toLowerCase();
if (topic.equals("time") || topic.equals("date")){
System.out.println("The time is " + Calendar.getInstance().getTime());
}
You code won't compile since the syntax is not correct in any case.
The answer is no, || operator works on boolean expressions and a String is not a boolean value.
The meaningful way to do it is the traditional way:
if (a.equals("hello") || a.equals("greetings") {
..
}
If you have many different alternatives for many different tokens then you should consider using a different approach, like a Map<String, Consumer<String>> so that you can do something like:
Map<String, Consumer<String>> mapping = new HashMap<>();
Consumer<String> greetings = s -> code;
mapping.put("hello", greetings);
mapping.put("greetings", greetings);
...
Consumer<String> mapped = mapping.get(a);
if (mapped != null)
mapped.accept(a);
if (yourString.equals("hello") || yourString.equals("greetings")){
//Execute code
}
If you want to compare your string with ignoring case. Use equalsIgnoreCase() method instead of equals()
The previous answers are correct and on point, but I'd like to change one thing just a bit:
if ("hello".equals(a) || "greetings".equals(a)) {
//...
}
That way, you are not risking NullPointerException (which would get thrown if a is null, because you can't execute a method on a null object). If you want to ignore the case, use equalsIgnoreCase(String).
Or, alternatively, use switch:
switch(a) {
case "hello": //do something
break;
case "greetings": //do something
break;
default: //handle case where there is no match, if needed
}
I found an answer to my question after some experimenting, Sorry about the confusion
scanner = new Scanner(System.in);
String topic = scanner.nextLine();
topic = topic.toLowerCase();
if (topic.contains("time") || topic.contains("date")){
System.out.println("The time is " + Calendar.getInstance().getTime());
}
Related
I've been searching around stackoverflow, and I've found a few other questions on converting a string to a boolean, but I can't make it work. Perhaps it is just the way I am trying to use it is incorrect.
Anyways, I am trying to convert two different input strings "M" or "I" in to boolean for use in an if statement. What is basically want the functionality to be is this:
// the text that is retrieved is assumed to be either"M" or "I"
M=Input.getText
I=Input.getText
If M shows the value "M",
do stuff here
else if I shows the value "I",
do stuff here
else if neither above are true,
throw an exception here
I've tried any number of "toBoolean"s and "Boolean.valueof"s, but none of what I try is working.
PS, Sorry for not having actual code to work with, this is my first step, and thus I haven't built anything up around this piece.
You can use String's methods to check for whether it contains a given literal value, equals it, or equals ignoring case.
A draft condition would be:
if ("myValue".equalsIgnoreCase(myText)) {
// TODO
}
else if ("myOtherValue".equalsIgnoreCase(myOtherText)) {
// TODO
}
else {
// TODO
}
Here is the documentation in java.lang.String:
equals
equalsIgnorecase
contains
You also want to check the many other methods, such as startsWith, endswith, etc. etc.
Use this for one boolean:
boolean b = (M.equals("M") || I.equals("I"));
Or this for two boolean:
boolean booleanM = (M.equals("M"));
boolean booleanI = (I.equals("I"));
if(booleanM){
//do stuff here
}else if(booleanI){
//do stuff here
}else{
//do stuff here where both are false
}
This is the faster way if you need to verify more than one time, only one time use this:
if(M.equals("M")){
//do stuff here
}else if(I.equals("I")){
//do stuff here
}else{
//do stuff here where both are false
}
You can simply use boolean b = Input.getText().equalsIgnoreCase("YourTrueString"). This method will detect if the input text is exactly the same as "YourTrueString". If not, it'll return false. This way anything that isn't true becomes false.
From your pseudo code
// the text that is retrieved is assumed to be either"M" or "I"
M=Input.getText
I=Input.getText
If M shows the value "M",
do stuff here
else if I shows the value "I",
do stuff here
else if neither above are true,
throw an exception here
To Java
// In its own method for reuse, in case you want to extend character support
public boolean match(String character, String match) {
return character.equals(match);
}
You can then invoke this simple method
String m = Input.getText();
String i = Input.getText();
if (match(m, "M")) {
do stuff here
} else if (match(i, "I")) {
do stuff here
} else {
throw an exception here
}
Is it possible to get multiple strings with .equals?
if(something.equals("String1 String2 String3")){
System.out.println(Something);
}
What I mean is:
if(choose.equals("DO IT")){
sysout blah blah blah
}
else if(choose.equals("DONT DO IT")){
...
}
No, but an alternative for many strings is to put the strings in a collection and do something like:
Set<String> strings = new HashSet<>();
strings.add("A");
strings.add("B");
strings.add("C");
if (strings.contains("D")) {
// ...
}
which is perhaps a little more concise. It's also null-safe wrt. the string you're looking to compare, which is often very useful.
Note further with Java 7 the switch statement works with strings, and that's useful if you wish to tie different actions to different strings.
If something is "String1 String2 String3" then it is equal.
If you mean contains, you can do
List<String> valid = Arrays.asList(string1, string2, string3);
if (valid.contains(something))
No you cannot. equals() takes only one object at a time.
As an alternative, you can try something like
if(something.equals("String1") || something.equals("String2") ||
something.equals("String3")) {
System.out.println(Something);
}
If you mean "can I test a string being equal to several strings in one operation", use regex:
if (something.matches("String1|String2|String3")) {
System.out.println(Something);
}
The pipe char | means "OR" in regex.
Note that in java (unlike many other languages) matches() must match the whole string - ie this is an "equals" comparison, not a "contains" comparison.
You can use a regex given the strings you match don't contain special regex characters, or are escaped.
Example:
Pattern p = Pattern.compile("^(String1|String2|String3)$");
if(p.matcher(something).find()) {
//do something
}
Or you can store the strings in a set/list and query the set:
Example:
HashSet<String> possible = new HashSet<String>();
possible.add("String1");
possible.add("String2");
possible.add("String3");
if(possible.contains(Something)) {
//do something
}
No, but you can use || to test multiple strings for equality:
if(something.equals("String1") || something.equals("String2") || something.equals("String3"))){
System.out.println(Something);
}
If you have gone through the javadocs it says
public boolean equals(Object obj); :
Indicates whether some other object is "equal to" this one.
It does not says that some other object is "equal to" these Objects.
Using equals() you can compare an Object with some other Object. It does not allow you to compare at once an Object with many other Objects. However if you want to compare an Object with many other Objects then you will need equals() for each comparasion
Well, if you want to check if there are any in such a string that don't match (aka all must match, albeit that doesn't really seem to make sense to me), then
String initString = "String1 String2 String3";
String[] splitStrings = initString.split(" ");
boolean match = true;
for(String string : splitStrings)
{
if(!string.equals(something))
{
match = false;
break;
}
}
if(match == true)
{
//did match all of them
}
else
{
//there was one that was not matched
}
If you want a "matches at least one" then it's just
String initString = "String1 String2 String3";
String[] splitStrings = initString.split(" ");
boolean match = false;
for(String string : splitStrings)
{
if(string.equals(something))
{
match = true;
break;
}
}
if(match == true)
{
//did match at least one of them
}
else
{
//didn't match any of them
}
But to be honest, Java 8 makes this simpler:
String something = "whatever";
String initString = "String1 String2 String3";
String[] splitStrings = initString.split(" ");
boolean matchAll = Arrays.stream(splitStrings).allMatch((x) -> x.equals(something));
boolean matchAny = Arrays.stream(splitStrings).anyMatch((x) -> x.equals(something));
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
The following statement just looks very messy when you have a lot of terms:
if(a.equals("x") || a.equals("y") || a.equals("z") || Any number of terms...... )
//Do something
Is there a cleaner way of performing the same action, I would like my code to be as readable as possible.
NOTE: x, y and z are just placeholders for any string of any length. There could be 20 string terms here of variable length in if condition each being OR'd together
What do you think looks "unclean" about it?
If you have a bunch of complicated boolean logic, you might separate the different parts of it into individual boolean variables and refer to them in the if statement.
Or you could create a function that takes your 'a' variable and returns a boolean. You'd just be hiding your logic in the method, but it would clean up your if statement.
Set<String> stuff = new HashSet<String>();
stuff.add("x");
stuff.add("y");
stuff.add("z");
if(stuff.contains(a)) {
//stuff
}
If this is a tight loop you can use a static Set.
static Set<String> stuff;
static {
stuff = new HashSet<String>();
stuff.add("x");
stuff.add("y");
stuff.add("z");
}
//Somewhere else in the cosmos
if(stuff.contains(a)) {
//stuff
}
And if you want to be extra sure nothing is getting modified while you're not looking.
Set<String> test = Collections.unmodifiableSet(new HashSet<String>() {
{
add("x");
add("y");
add("z");
}
});
If you just want to get some logic in there for a handful of hard coded conditions then one of the switch or if statement with newlines solutions might be better. But if you have a lot of conditions then it might be good to separate your configuration from logic.
Alternatively, if you are using Java 7+ you can use strings in switch/case. For example (I extracted this from an Oracle doc and modified)
switch (str) {
case "x":
case "y":
case "z":
//do action
break;
default:
throw new IllegalArgumentException("argument not matched "+str);
}
Here is the link
Use a regular expression
If (a.matches("[xyz]")){
// matches either "x", "y", or "z"
or, for longer strings,
If (a.matches("one|two|three")){
// matches either "one", "two" or "three"
But this is computationally expensive, but probably not much worse than instantiating a set etc. But it's the clearest way I can think of.
But in the end, the nicest way is probably to leave things as they are, with an adjustment to the formatting:
if (a.equals("x") ||
a.equals("y") ||
a.equals("z")
){
There is then absolutely no ambiguity in what the code is doing and so your code will be easier to maintain. If performance matters, you can even put the most likely occurrences towards the top of the list.
Reaching for semantics
On a semantic level, what you are checking for is set membership. However, you implement it on a very low level, basically inlining all the code needed to achieve the check. Apart from forcing the reader to infer the intent behind that massive condition, a prominent issue with such an approach is the large number of degrees of freedom in a general Boolean expression: to be sure the whole thing amounts to just checking set membership, one must carefully inspect each clause, minding any parentheses, misspellings of the repeated variable name, and more.
Each loose degree of freedom means exposure to not just one more bug, but to one more class of bugs.
An approach which uses an explicit set would have these advantages:
clear and explicit semantics;
tight constraint on the degrees of freedom to look after;
O(1) time complexity vs. O(n) complexity of your code.
This is the code needed to implement a set-based idiom:
static final Set<String> matches =
unmodifiableSet(new HashSet<>(asList("a","b","c")));
...
if (matches.contains(a)) // do something;
*I'm implying import static java.util.Arrays.asList and import static java.util.Collections.unmodifiableSet
Readability Is Mostly Formatting
Not readable...
if(a.equals("x") || a.equals("y") || a.equals("z") || Any number of terms...... )
//Do something
Now easy to real...
if(a.equals("x") ||
a.equals("y") ||
a.equals("z") ||
Any number of terms...... )
//Do something
Readability is very subjective to the person reading the source code.
If I came across code that implements collections, loops or one of the many other complicated answers here. I'd shake my head in disbelieve.
Separate The Logic From The Problem
You are mixing two different things. There is the problem of making the business logic easy to read, and the problem of implementing the business logic.
if(validState(a))
// Do something
How you implement validState doesn't matter. What's important is that code with the if statement is readable as business logic. It should not be a long chain of Boolean operations that hide the intent of what is happening.
Here is an example of readable business logic.
if(!isCreditCard(a)) {
return false;
}
if(isExpired(a)) {
return false;
}
return paymentAuthorized(a);
At some level there has to be code that processes basic logic, strings, arrays, etc.. etc.. but it shouldn't be at this level.
If you find you often have to check if a string is equal to a bunch of other strings. Put that code into a string utility class. Separate it from your work and keep your code readable. By ensuring it shows what you're really trying to do.
You can use Arrays.asList().This is the simplest approach and less verbosity.
Arrays.asList("x","y","z"...).contains(a)
For performance reason if your collection is too big you could put data in a HashSet cause searching there is in constant time.
Example make your own util method
public final class Utils{
private Utils(){}//don't let instantiate
public static <T> boolean contains(T a,T ... x){
return new HashSet<>(Arrays.asList(x)).contains(a);
}
}
Then in your client code:
if(Utils.contains(a,"x","y","z","n")){
//execute some code
}
With a little bit of help, you can get the syntactic sugar of a nicer if-statement with just a tiny bit of overhead. To elaborate on Tim's recommendation and Jesko's recommendation a tad further...
public abstract class Criteria {
public boolean matchesAny( Object... objects ) {
for( int i = 0, count = objects.length; i < count; i++ ) {
Object object = objects[i];
if( matches( object ) ) {
return true;
}
}
return false;
}
public boolean matchesAll( Object... objects ) {
for( int i = 0, count = objects.length; i < count; i++ ) {
Object object = objects[i];
if( !matches( object ) ) {
return false;
}
}
return true;
}
public abstract boolean matches( Object object );
}
public class Identity extends Criteria {
public static Identity of( Object self ) {
return new Identity( self );
}
private final Object self;
public Identity( Object self ) {
this.self = self;
}
#Override
public boolean matches( Object object ) {
return self != null ? self.equals( object ) : object == null;
}
}
Your if-statement would then look like this:
if( Identity.of( a ).matchesAny( "x", "y", "z" ) ) {
...
}
This is sort of a middle ground between having a generic syntax for this sort of conditional matching and having the expression describe a specific intent. Following this pattern also lets you perform the same sort of matching using criteria other than equality, much like how Comparators are designed.
Even with the improved syntax, this conditional expression is still just a little bit too complex. Further refactoring might lead to externalizing the terms "x", "y", "z" and moving the expression into a method whose name clearly defines its intent:
private static final String [] IMPORTANT_TERMS = {
"x",
"y",
"z"
};
public boolean isImportant( String term ) {
return Identity.of( term ).matchesAny( IMPORTANT_TERMS );
}
...and your original if-statement would finally be reduced to...
if( isImportant( a ) ) {
...
}
That's much better, and now the method containing your conditional expression can more readily focus on Doing One Thing.
Independent of what you are trying to achieve, this
if(a.equals("x") || a.equals("y") || a.equals("z") || Any number of terms...... )
//Do something
is always messy and unclean. In the first place it is just too long to make sense of it quickly.
The simplest solution for me would be to express your intend instead of being explicit.
Try to do this instead:
public class SomeClass{
public void SomeMethod(){
if ( matchesSignificantChar(a) ){
//doSomething
}
}
private bool matchesSignificantChar(String s){
return (s.equals("x") || s.equals("y") || s.equals("z") || Any number of terms...... )
}
}
This simplifies the scope of your conditional statement and makes it easier to understand while moving the complexity to a much smaller and named scope, that is headed by your intend.
However, this is still not very extensible. If you try to make it cleaner, you can extract the boolean method into another class and pass it as a delegate to SomeClass'es Constructor or even to SomeMethod. Also you can look into the Strategy Pattern for even more exensiblity.
Keep in mind that as a programmer you will spend much more time reading code (not only yours) than writing it, so creating better understandable code will pay off in the long run.
I use following pattern
boolean cond = false; // Name this variable reasonably
cond = cond || a.equals("x");
cond = cond || a.equals("y");
cond = cond || a.equals("z");
// Any number of terms......
if (cond) {
// ...
}
Note: no objects created on the heap. Also you can use any conditions, not only "equals".
In ruby you can use operator ||= for this purpose like cond ||= a.equals("x").
The Set answer is good. When not comparing for membership of a collection you can also separate out some or all of the conditional statement into methods. For example
if (inBounds(x) && shouldProcess(x) ) {
}
If a is guaranteed to be of length 1, you could do:
if ("xyz".indexOf(a) != -1)
One really nice way to do something like this is to use ASCII values, assuming your actual case here is where a is a char or a single character string. Convert a to its ASCII integer equivalent, then use something like this:
If you want to check that a is either "t", "u", "v", ... , "z", then do.....
If (val >= 116 && val <= 122) {//code here}
I prefer to use regexp like few guys wrote upper.
But also you can use next code
private boolean isOneMoreEquals(Object arg, Object... conditions) {
if (conditions == null || arg == null) {
return false;
}
for (int i = 0, d = conditions.length; i < d; i++) {
if (arg.equals(conditions[i])) {
return true;
}
}
return false;
}
so your code will be next:
if (isOneMoreEquals(a, "x", "y", "z") {
//do something
}
Assuming that your "x", "y", and "z" can be of arbitrary length, you can use
if (0 <= java.util.Arrays.binarySearch(new String[] { "x", "y", "z" }, a)) {
// Do something
}
Just make sure that you list your items in lexicographic order, as required by binarySearch(). That should be compatible all the way back to Java 1.2, and it should be more efficient than the solutions that use Java Collections.
Of course, if your "x", "y", and "z" are all single characters, and a is also a character, you can use if (0 <= "xyz".indexOf(a)) { ... } or
switch (a) {
case 'x': case 'y': case 'z':
// Do something
}
If x,y,z... is Consecutiveļ¼ you can use if(a >= 'x' && a <= '...'), if not, you can use ArrayList or just Arrays.
I think that cleanest and fastest way is to put values in array.
String[] values={"value1","value2","value3"};
for (string value : values) {
if (a.equals(value){
//Some code
}
}
this is my first so I'll try to add as much info as possible so I don't get yelled at. :-)
What I am trying to do is I have 2 variables that grab text from 2 fields and take only the first character from each and assign it to those values.
This is the code that I use to get the strings. They are 2 separate calls as you would.
try { var_ContactSurname = var_ContactSurname.substring(0,1);
}
catch (Exception e){
}
I have the above again with a different variable. Now to this point it does what I want. It grabs the first letter from the fields and assigns it to the variables.
So at this point I have two variables (say with an example charater of D and R).
var_ContactSurname = R
var_ContactLicenceNumber = D
What I want to do is compare those two variables and if they match I want to return a value of TRUE, else FALSE if they don't match.
That value has to be a string as well and be assigned to a new variable called var_ContactValidate.
if (var_ContactLicenceNumber.toLowerCase().equals()var_ContactSurname.toLowerCase()){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
No you may notice that there might be some code missing. I am using a rules engine that does a lot of the functions for me. I can use raw Java code to do other things (like this compare)...but that's the compare that I am having a problem with.
Any ideas for that compare would be greatly appreciated.
Thanks.
i would use the String method equalsIgnoreCase()
to assign a value to a field, use a single =, not double (==).
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname){
var_ContactValidate = "TRUE";
}
else {
var_ContactValidate = "FALSE";
}
check it
In addition to what already said - a simpler & more elegant version (without the if condition) could be:
var_ContactValidate = Boolean.toString(
var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname))
.toUpperCase();
Change your whole piece of code to:
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname)){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
This combines the case insensitivity that you want, and passes through the second string as an argument of the .equalsIgnoreCase function.
Also, I am not sure what you are trying to do with the line:
var_ContactValidate == "TRUE";
If you want to assign var_ContactValidate to "TRUE" then use a single equals sign '=' as a double equals '==' compares the values instead. You may also considering using a boolean rather than a string in this case.
Here is an implementation that also checks for null values and empty Strings:
public class SurnameAndLicenseValidator {
public static void main(String[] args) {
// FALSE
validateSurnameAndLicense(null, "jb78hq");
validateSurnameAndLicense("Johnson", null);
validateSurnameAndLicense(null, null);
validateSurnameAndLicense("", "jb78hq");
validateSurnameAndLicense("Johnson", "");
validateSurnameAndLicense("", "");
validateSurnameAndLicense("johnson", "xb78hq");
// TRUE
validateSurnameAndLicense("Johnson", "jb78hq");
validateSurnameAndLicense("johnson", "jb78hq");
}
private static String validateSurnameAndLicense(String surname,
String license) {
String result;
if (surname != null
&& surname.length() > 0
&& license != null
&& license.length() > 0
&& Character.toUpperCase(surname.charAt(0)) == Character
.toUpperCase(license.charAt(0))) {
result = "TRUE";
} else {
result = "FALSE";
}
System.out.println(surname + " " + license + " " + result);
return result;
}
}
The main method is used as a unit test here. You might want to extract a real JUnit test from it, if you are into that kind of thing.
I'm having trouble working out how to count instances of Values in a HashMap.
I have seen that there is methods attached to the Object class that look as if they are able to help me, so I've tried to cast those in to work but I must be doing something wrong somewhere.
If there's an easier way, I haven't found it yet. NB: Library is my HashMap.
public void borrowBooks(String id, String name, String sid, String sname) {
if((getKeyFromValue(Books, name).equals(id))&&(getKeyFromValue(Students, sname).equals(sid))){
if((Object)Library.countValues(sid)!=5){
Library.put(id, sid);
}
else{
System.out.println("You have exceeded your quota. Return a book before you take one out." );
}
}
}
Which doc are you looking at ? The Javadoc for Hashmap doesn't specify a countValues() method.
I think you want a HashMap<String, List<String>> so you store a list of books per student (if I'm reading your code correctly).
You'll have to create a list per student and put that into the HashMap, but then you can simply count the entries in the List using List.size().
e.g.
if (Library.get(id) == null) {
Library.put(id, new ArrayList<String>());
}
List<String> books = Library.get(id);
int number = books.size() // gives you the size
Ignoring threading etc.
First: There is (almost) no point in ever casting anything to Object. Since everything extends Object, you can always access the methods without casting.
Second: The way you're casting actually casts the return value, not the Library. If you were doing a cast that was really necessary, you would need an extra set of parentheses:
if(((Object)Library).countValues(sid) != 5)
Third: There is no countValues method in either HashMap or Object. You'll have to make your own.
This is the general algorithm to use (I'm hesitant to post code because this looks like homework):
initialize count to 0
for each entry in Library:
if the value is what you want:
increment the count
int count = 0;
for(String str : Library.values())
{
if(str == sid)
count++;
if(count == 5)
break;
}
if(count < 5)
Library.put(id, sid);
else
System.out.println("You have exceeded your quota. Return a book before you take one out." );