if statement should print string values - java

How do I print result from if statements in Java? This result should be assigned to some variable, that variable should print result in string. Currently, my code is like this. I want to store simple & extended into a single variable, so that i should able to call this variable anywhere in the program. There it should print "simple" or "extended".
if(loc[i]==1) {
System.out.println("simple");
}
else if(loc[i]>1) {
System.out.println("extended");
}

You mean like this:
String mode;
if(loc[i]==1)
mode = "simple";
else if(loc[i]>1)
mode = "extended";
else
mode = "error";
System.out.println(mode);

How about
String s = (loc[i]==1 ? "simple" : (loc[i]>1 ? "extended" : null));

If I understood you correctly you need following
private static final SIMPLE_STRING = "simple";
private static final EXTENDED_STRING = "extended";
if(loc[i]==1) {
System.out.println(SIMPLE_STRING );
}
else if(loc[i]>1) {
System.out.println(EXTENDED_STRING );
}

String type;
if( loc[i] == 1 )
{
type = "simple";
}
else if( loc[i] > 1)
{
type = "extended";
}
else
{
type = null;
}
// variable 'type' can now be used in the same block of code
System.out.println( type );
If you want to use this variable anywhere in your program, you will have to either declare the variable at a higher scope to be accessible or return this variable from this code block.

Related

How to avoid many if-else statements

I have a class like this..
Class A {
public void someNullCheckingMethod(Student stu) {
if (stu.getName() != null) {
String name = stu.getName();
} else {
// get name from other source(its something like
// fallback)
}
if (stu.getId() != null) {
String id = stu.getId();
} else {
// get id from other source(its something like
// fallback)
}
if (stu.getAddress() != null) {
String address = stu.getAddress();
} else {
// get address from other source(its something like
// fallback)
}
if (stu.getCity() != null) {
String city = stu.getCity();
} else {
// get city from other source(its something like
// fallback)
}
if (stu.getGender() != null) {
String gender = stu.getGender();
} else {
// get gender from other source(its something like
// fallback))
}
}
}
is there a way to avoid too many if statements? As you can see here I am checking null condition for each property but i don't want many checks to get desired result just want to reduce if conditions as well as want to get same desired result whatever I will get by putting all these if conditions.
Since you don't provide any context there's a few things you can do based on some assumptions.
Assumption one:
if the values are initialized as null
String name;
// or
String name = null;
Then you can just assign the values and ignore if the fields are null or not since the class members are null already.
String name = stu.getName(); // String name = "Some Name" OR null, depending on return value of method
Assumption two:
If you just want to avoid the if statements you can go with ternary operators
String name = stu.getName() != null ? stu.getName() : null; // Or some other default value
There are a few other methods that pops into my mind as well but without more context they are a bit useless at this point.
You could at least reduce the "verbosity" with Optional.
String name;
if (stu.getName() != null) {
name = stu.getName();
} else {
name = "default"
}
Would become
String name = Optional.ofNullable(stu.getName()).orElse("default");
Th choice is yours to return an Optional directly from the POJO Student for any value that could be null.
This would give a cleaner solution :
String name = stu.getName().orElse("default");
If getName looks like :
public Optional<String> getName(){
return Optional.ofNullable(name);
}
If using an external library is an option, then you should take a look at Dozer or MapStruct.

Add null-like value to String in Java

I am writing test method like setTask(Task task). And Task object has several fields, e.g.
public String vehicle;
Method setTask should be used in different test-cases, so I'd like to have an options for this field to accept values:
null - the method should not do anything in this particulare case;
some string value - e.g. "", "Hello, World!", "Iso Isetta", ...
random - a value that indicates (as well as null indicates "no changes") that a random value should be selected for a drop-down list corresponding to this field.
So what can I do to make String to be SpecialString which could accept values null, random & some string value? (BTW: I don't want to set it to string value "RANDOM", and chech whether the value is equal to "RANDOM"-string)
UPDATE: I don't mean random like random value from a set of values, I mean random as well as null and this is for setTask() to handle random (select random from drop-down), and not to pass a random string from a set of values.
Pseudocode:
Task task = new Task();
task.vehicle = random; // as well as null
setTask(task)
in setTask(Task task):
if (task.vehicle == null) {
//skip
} else if (task.vehicle == random) {
// get possible values from drop-down list
// select one of them
} else {
// select value from drop-down list which is equal to task.vehicle
}
Don't assign a fixed String but use a Supplier<String> which can generate a String dynamically:
public Supplier<String> vehicleSupplier;
This, you can assign a generator function as you request:
static Supplier<String> nullSupplier () { return () -> null; }
static Supplier<String> fixedValueSupplier (String value) { return () -> value; }
static Supplier<String> randomSupplier (String... values) {
int index = ThreadLocalRandom.current().nextInt(values.length) -1;
return index > 0 && index < values.length ? values[index] : null;
}
In use, this looks like:
task.setVehicleSupplier(nullSupplier()); // or
task.setVehicleSupplier(fixedValueSupplier("value")); // or
task.setVehicleSupplier(randomSupplier("", "Hello, World!", "Iso Isetta"));
and you can get the String by
String value = task.vehicleSupplier().get();
or hide the implementation in a getter function
class Task {
// ...
private Supplier<String> vehicleSupplier;
public void setVehicleSupplier(Supplier<String> s) {
vehicleSupplier = s;
}
public String getVehicle() {
return vehicleSupplier != null ? vehicleSupplier.get() : null;
}
// ...
}
What you may want to do is to create an object that wraps a string as well as some information about whether or not it's a special value. Something along the lines of...
public class Special<T> {
public enum Type {
NOTHING, RANDOM, SPECIFIC
}
private final Type type;
private final T specificValue;
public Special(Type type, T specificValue) {
this.type = type;
this.specificValue = specificValue;
}
public Type getType() {
return type;
}
public T getSpecificValue() {
if (type != SPECIFIC) {
throw new IllegalStateException("Value is not specific");
}
return specificValue;
}
}
The class above could be used like so:
Special<String> a = new Special<>(Special.Type.NOTHING, null);
Special<String> b = new Special<>(Special.Type.SPECIFIC, "Hello");
if (b.getType() == Special.Type.RANDOM) {
// do something
}else if (b.getType() == Special.Type.SPECIFIC) {
String val = b.getSpecificValue();
// do something else
}
A slightly more polished variant of the thing above is probably the best way, but there is a way, a much uglier way, to do it using nothing but a String field.
What you could do is to have a "magical" string instance that behaves differently from all other string instances, despite having the same value. This would be done by having something like
static final String SPECIAL_VALUE_RANDOM = new String("random");
Note the use of the String constructor, which ensures that the string becomes a unique, non-interned instance. You can then say if (vehicle == SPECIAL_VALUE_RANDOM) { ... } (note the use of == instead of .equals()) to check if that specific instance (rather than any other string that says "random") was used.
Again, this is not a particularly good way of doing this, especially if you intend to do this more than once ever. I would strongly suggest something closer to the first way.

Java -why can't I set a value in an array to null after I return it?

I'm returning a value from an array, but I want to set the value to null afterwards . The problem is I keep getting an error. Why is this?
public Book retrieveBookFromBookshelf (String title)
{
for (int i = 0; i < this.books.length; i++) {
if (this.books[i].getTitle().equals(title)) {
return this.books[i];
this.books[i] = null;
}
}
return null;
}
Because before you set the value to null, you return from the function. Once return is executed, nothing else is done in the current function and control is given back to the caller function.
What you're attempting to do is not possible. instead, cache the reference to this.books[i].
if (this.books[i].getTitle().equals(title)) {
Book book = this.books[i]; // cache the reference
this.books[i] = null;
return book;
}
You can't normally run statements after returning. You need to store the value in a temporary variable:
Book result = this.books[i];
this.books[i] = null;
return result;
Alternatively, you can return in a try block and set it to null inside finally:
try {
return this.books[i];
} finally {
this.books[i] = null;
}
But I think that's a little overkill for your use case.

Java: Method that returns either String or int

A part of a small program I am coding:
String maxs = "";
int maxi = 0;
At this part I defined two variables as int and String.
public Class(String max){
try {
this.maxi = Integer.parseInt(max);
}catch (Exception e){
this.maxs = max;
}
}
I think this way I will get to define one of both variables, if the String does not parse to int it will be saved as normal String.
Now I need to check what I need to return:
private TypeOfReturn getMax(){
if(this.maxi == 0){
// return maxs (return String)
} else if (this.maxs.equals("")) {
// return maxi (return int)
} else return null;
}
The quastion is, how do I fill the missing parts of the method getMax()?
Is it even possiable in Java?
Use Object instead of TypeOfReturn
You can change the TypeoOfReturn to Object and then return the respective types.
Another way to find out fast if a string is a number or not, which is the main part of your program, is to use the lambda expressions in java 8 like this:
String max = "123";
boolean isNumber = max.chars().allMatch(Character::isDigit);
System.out.println(isNumber);
Which will give you the output
true
Make your TypeOfReturn as String object type and convert the maxi as String and return that String in your else if condition.
Note: you cannot return both the int and String in the Same method.

how to write function for multiple if-else statements

I am new to Java. I have lots of multiple if-else statements. For code optimization purpose I need to write one function for all if else logic.
if (obj.getJSONObject("page_1").has("city")) {
sn.city = (String) obj.getJSONObject("page_1").get("city").toString();
} else {
sn.city = null;
}
// param 2 - locality
if (obj.getJSONObject("page_1").has("locality")) {
locality = (String) obj.getJSONObject("page_1").get("locality").toString();
} else {
locality = null;
}
I have like 110 if -else statements. I don't have any idea how to optimize the code.
I might write a function something like:
static String getToStringOrNull(JSONObject parent, String key) {
return parent.has(key) ? parent.get(key).toString() : null;
}
which you can then call like
sn.city = getToStringOrNull(obj.getJSONObject("page_1"), "city");
locality = getToStringOrNull(obj.getJSONObject("page_1"), "locality");
I think the best use would be this notation (ternary operator):
sn.city = (obj.getJSONObject("page_1").has("city")) ?
(String) obj.getJSONObject("page_1").get("city").toString() : null;
The part before ? stands for the if-statement, the second part if the condition was fulfilled and the last part otherwise.
For all direct fields of your class, you may use reflection (and you could do the same work on the sn object if you want ) :
Class aClass = this.getClass();
Field[] fields = aClass.getFields();
for (Field field : fields) {
String value = (obj.getJSONObject("page_1").has(field.getName())) ?
(String) obj.getJSONObject("page_1").get(field.getName()).toString() : null;
field.set(this, value);
}

Categories

Resources