Efficient way to build a key using two strings in java? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
Below is the code I have written to build a key using two strings. If either of them is null, empty or blank use the other string to build the key. However if both of them does not qualify, return an empty string. I would like to write a better and efficient piece of code. Here is my sample code
if (!StringAssistant.isBlank(string1) && !StringAssistant.isBlank(string2)) {
return StringAssistant.append(string1, string2);
}
if (StringAssistant.isBlank(string1) && !StringAssistant.isBlank(string2)) {
return string2;
}
if (!StringAssistant.isBlank(string1) && StringAssistant.isBlank(string2)) {
return string1;
}
return "";

You may do something as "simple" as :
return StringAssistant.append(StringAssistant.isBlank(string1)?"":string1,StringAssistant.isBlank(string2)?"":string2);

Simply append the two string and return the value
return string1+string2;
or if you want to use your StringAssistant.append
return return StringAssistant.append(string1, string2);
Notice that the empty string doesn't has an impact on the return value. So if you append the string and return it will result the same.
If the string can be null then you need to handle the null value separately. if either string is null then you can return an empty string. You can handle it in your append method.

You can refactor the code as shown below, I suggest you evaluate the isBlank for the both the strings first (so that for large strings you would get the results quicker):
boolean string1Blank = !StringAssistant.isBlank(string1);
boolean string2Blank = !StringAssistant.isBlank(string2);
if(string1Blank && string2Blank) {
return StringAssistant.append(string1, string2);
} else if(string1Blank) {
return string2;
} else if(string2Blank) {
return string1;
} else {
return "";
}

Related

How to write Conditional Statement inside a Try Block in JAVA? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am new to Java so please don't mind the syntax errors. I want to check if string1 OR string2 is null. If one of them is null then I want to throw a NullPointerException. Also, the return type of my method should be String.
public String handleException(Activity a) {
try {
if(a.string1.equals(null) || a.string2.equals(null))
throw new NullPointerException();
}
catch(NullPointerException e) {
return "Null value found";
}
}
I think you are trying to do that:
public String handleException(Activity a) {
if(a.string1 == null || a.string2 == null) {
// if string1 or string2 is null, throw your exception
throw new NullPointerException("Null value found");
}
// do something now that you know your strings aren't null
return "something";
}
To check if a string is null, you can just use ==
One suggestion is to separate the error handling from the business logic:
public String handleException(Activity activity) {
try {
handleActivity(activity);
}
catch(NullPointerException e) {
return "Null value found";
}
}
private void handleActivity(Activity activity) {
// or some other logic that might cause a NullPointerException
System.out.println(activity.string1.length());
System.out.println(activity.string2.length());
}
But normally NPE's are not caught explicitly, we try to write code that doesn't cause them. There are several ways to check, like using JSR 380:
public class User {
#NotNull(message = "Name cannot be null")
private String name;
You can also check yourself:
if (activity.string1 == null) {
...
In this case you should use == because null is not an Object (and cannot be autoboxed as an Object) and therefore cannot be evaluated by the equals(Object) method. Null is a special value (AKA the billion dollar mistake) which indicates that a variable which is declared as an Object actually refers to nothing.
Technically speaking you don't even need a try-catch block for this operation
You could simply do
public String handleException(Activity a) {
if(a.string1 == null || a.string2 == null){
return "Null value found";
}
// return normal case value
}
But from what I understood you just want to see how try-catch blocks work, so maybe you could explain more what you need exactly.

How to turn recursion into iteration? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I get a horrific stackoverflowerror, and figured it was my deep recursion causing it (well, the debugger helped with that...). Can anyone guide me in turning my recursion into a loop?
H<V>.Pair currPair = (H<V>.Pair) arr[startPos];
if (arr[startPos] == null) {
return null;
}
if (currPair.key.equals(key)) {
return currPair.value;
} else {
return find(gNL(startPos, ++stepNum, key), key, stepNum);
}
}
More specifically, return find(getNextLocation(startPos, ++stepNum, key), key, stepNum); causes the recursion.
This seems to be equivalent:
private V find(int startPos, String key, int stepNum) {
Hashtable<V>.Pair p;
boolean finished = false;
do {
p = (Hashtable<V>.Pair) arr[startPos];
if (p == null || p.key.equals(key)) {
finished = true;
} else {
startPos = getNextLocation(startPos, ++stepNum, key);
}
} while( ! finished);
return p == null ? null : p.value;
}
I believe this gets you there:
private V find(int startPos, String key, int stepNum) {
Hashtable<V>.Pair currPair = arr[startPos];
while ((currPair != null) && !currPair.key.equals(key)) {
stepNum++;
int nextPos = getNextLocation(startPos, stepNum, key);
currPair = arr[nextPos];
}
return (currPair == null)
? null
: currPair.value;
}
The "trick" is to put the conditions you used to end recursion into the loop condition. Note that because your algorithm doesn't use the intermediate results in any way as some other recursive algorithms do, the translation is quite straightforward. This will not work every time with all recursive algorithms, sometimes you'll need to add a data structure to hold your intermediate results.

I need help making a java constructor that akes a string and initilizes the value var with appropriate in [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
so sorry if my question is dumb but i haven't done java in 2 years. I'm working in my hw right now and i'm one method away from being done. but one of my constructor is wrong and idk where. thanks in advance!
the value variable is a private integer.
so far i have:
public FancyInt(String a) {
value = "";
a = this.value;
}
basically this constructor takes a string and initalizes the value to the appropriate int
Firstly if you want to equal "value" TO "a", you must write:
this.value = a;
in Java (and a lot of programming languages), you must write variable that you change before equal mark.
Second, if you will make "value" Integer. You must change it to int first:
try {
this.value = Integer.parseInt(a);
} catch (NumberFormatException e) {
e.printStackTrace();
}
Third, if "value" is an Integer. You must define that with numbers:
value = ""; //if value is an Integer, delete this line.
If you say that the variable "value" is a Integer, then your code cannot compile because you are assigning a String (in this case, an empty string "") to a Integer.
According to your last sentence, I think your code should look like this:
public FancyInt(String a) {
this.value = isInteger(a)? Integer.parseInt(a) : 0;
}
private boolean isInteger(String val) {
try{
Integer.parseInt(val);
return true;
}
catch (NumberFormatException e) {
return false;
}
}
You can change the implementation of the isInteger method, in this link Determine if a String is an Integer in Java you have multiple options that could help you.

Easiest way to find the element is present in ENUM or not in JAVA? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I need to find the specific string element is present in ENUM or not at runtime using java and based on that take action. What is the efficient way to do so.
A very minimal example given your requirements. Here is some documentation for Enums that you should look at as well. Enum info
Given the enum below:
enum TestEnum {
FOO,
BAR
}
You could simply call valueOf to determine if the String is a valid for that enum.
public boolean exampleTest(final String value) {
try {
TestEnum.valueOf(value);
return true;
} catch (final IllegalArgumentException | NullPointerException) {
// Log if desired
return false;
}
}
Note: Enum#valueOf is case sensitive so the String argument must match exactly.
exampleTest(“FOO”); // true
exampleTest(null); // false
exampleTest(“BAR”); // true
exampleTest(“bar”); // false
You can do like below -
public enum Direction {
NORTH("North"),
EAST("East"),
SOUTH("South"),
WEST("West")
private String dir;
Direction(String dir) {
this.dir = dir;
}
public String getDir() {
return dir;
}
}
to check with specific string you can do like below -
for(Direction dir : Direction.values())
{
//check your condition here
System.out.println(dir.name() + " :: "+ env.getDir());
}

How ArrayList contains method work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I've a doubt about how ArrayList contains method works. Let's take an example:
List<String> lstStr = new ArrayList<String>();
String tempStr1 = new String("1");
String tempStr2 = new String("1");
lstStr.add(tempStr1);
if (lst.contains(tempStr2))
System.out.println("contains");
else
System.out.println("not contains");
it returns 'not contains'.
Another example:
List<LinkProfileGeo> lst = new ArrayList<LinkProfileGeo>();
LinkProfileGeo temp1 = new LinkProfileGeo();
temp1.setGeoCode("1");
LinkProfileGeo temp2 = new LinkProfileGeo();
temp2.setGeoCode("1");
lst.add(temp1);
if (lst.contains(temp2))
System.out.println("contains");
else
System.out.println("not contains");
It returns contains. So how does contains method works ?
Thanks
You are adding your string to the list lstStr
lstStr.add(tempStr1);
but you are using contains method on lst
if (lst.contains(tempStr2))
Your idea of testing is correct, as contains internally uses equals to find the element, so if the string is matched using equals then it should return true. But it seems you are using two different lists, one for adding and another one for checking contains.
Here is the relevant source code from ArrayList if you're interested. As #user2777005 noted, you had a typo in your code. You should use lstStr.contains(), NOT lst.contains().
public int indexOf(Object o) {
if (o==null) {
for (int i=0; i<a.length; i++)
if (a[i]==null)
return i;
} else {
for (int i=0; i<a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
public boolean contains(Object o) {
return indexOf(o) != -1;
}
the second part is a duplicate of: How does a ArrayList's contains() method evaluate objects?
You need to override the equals method to make it work as you desire.
in first section of code :
String tempStr1 = new String("1");
String tempStr2 = new String("1");
both tempStr1 and tempStr2 refer two different-2 object of string. after that String object that is refered by tempStr1 is added to the List by the codelstStr.add(tempStr1); .so the List have only one String object that is reffered by tempStr1 not tempStr2.but
contains(); method work on equals() method.that is lstStr.contains(temp2); return true if content of String object which is refered by temp2 is same as the one of content of String object which is added to the List and return false when matching not found.here lstStr.contains(temp2);return true because content of String object temp2 is equal to content of String object temp1 which is added to List.but in your code insteed of lstStr.contains(temp2); it is mentioned as:
lst.contains(temp2);
Here you are using different List reference variable (lst) instead of (lstStr).thats why it return false and executed else part.
in 2nd section of code setGeoCode() is not defined.

Categories

Resources