Can there be if without else in java

Alternative of if-else and switch statements

Now if I am asked not to use either of if-else and switch case statements, then what can be done? The code can be done in either Java or JavaScript.

Use a dictionary for each key you will have have list of functions as value and based on the key you pick the functions in list and iterate the list and call each function.

I will never understand the pedagogical reasons for asking students to «do X, but without using Y, the clearly correct method, or Z another valid, if awkward solution»

«in either Java or JavaScript» makes no sense. They are two very different languages with two very different domains. To answer your question, both languages supply several multiway ifs: if-then-elseif-else and some sort of switch . Your current implementation is defective because it hits each if test rather than bailing out after the first match. That’s probably what the instructor is getting at.

10 Answers 10

If you can use JavaScript, you can use a object with functions:

function doSomething(i) < var obj = <>; obj[12] = function () < // order should be same up(); left(); stop(); >; obj[304] = function () < // order should be same right(); up(); stop(); >; obj[962] = function () < // order should be same down(); left(); up(); stop(); >; // apparently we can't use any conditional statements try < obj[i](); >catch (e) <> > 

If only if and switch statements aren’t allowed, replace all the if statements with the logical AND operator ( && ):

Читайте также:  Php убрать последний пробел

Just want to point out that the second suggestion only works in languages that use short-circuit evaluation: en.wikipedia.org/wiki/Short-circuit_evaluation from the top of my head only pascal does not use it.

Here is a simple way to accomplish this in JavaScript:

function up() < console.log("up"); >function down() < console.log("down"); >function left() < console.log("left"); >function right() < console.log("right"); >function stop() < console.log("stop"); >var fnmaps = < 12: [up, left, stop], 304: [right, up, stop], 962: [down, left, up, stop] >; function doSomething(i) < var fnmap = fnmaps[i] || [], j; for (j = 0; j < fnmap.length; j++) < fnmap[j](); >> doSomething(12); doSomething(304); doSomething(962); 

Functions can be added/ordered simply by editing the map variable.

You can make a dictionary of input-to-action. In Java this would be a Map , with, for instance*:

Then, you can get the appropriate Runnable and run it:

Runnable action = map.get(i); if (action != null) < action.run(); >else < // some default action // This is the "default" case in a switch, or the "else" in an if-else >

The if-else there isn’t strictly necessary, but without it, you’ll get a NullPointerException if i isn’t an expected value — that is, one of the values you put into the map.

The idea is similar in JavaScript, though with objects instead of Map s, functions (probably anonymous) instead of Runnable s, etc.

This code is for Java 8. In Java 7 and below, you’d do:

@Puru— The idea works in Java 7 just as well. But yes, you’ll need to create an anonymous class instead of using a lambda.

@sura True, although it’s not required if you’re confident that i is always an expected value. (And if you’re wrong about that, you’ll get a NullPointerException at action.run() .)

@BrianS You could, but it’s a generally a bad idea. If the Runnable itself has a bug and throws a NPE, you’d never know because of that catch-and-ignore. Much better to let that propagate up so that something can yell at you about it.

Who says you have to ignore the exception? (Not that I think try/catch is a good substitute for if/else, merely that in this instance it can, and meets the OP’s requirements.)

Then do it with while and break, there is no other way without condition check

public void doSomething(int i) < while(i == 12) < // order should be same up(); left(); stop(); break; >while(i == 304) < // order should be same right(); up(); stop(); break; >while(i == 962) < // order should be same down(); left(); up(); stop(); break; >> 

Wahahahahaha, you saved my day 🙂 This should work, no way to test right now..

public void doSomething(int i) < try < int x = 1/(12-i); // fails for i==12 >catch (ArithmeticException e)
// define ur actions here var actions = < "12" : function () < up(); left(); stop(); >, "304" : function () < right(); up(); stop(); >, "962" : function () < down(); left(); up(); stop(); >>; function doSomething(i) < var fn = actions[i]; try < fn(); >catch (err) < console.error(err); >> // doSomething(12); //invoke here 

Look, naturally you should inspect a conditional statement with a conditional expression! Now, if you don’t want to do this, you can do it unnaturally like this:

first do this for all methods (up,down. )

java.lang.reflect.Method method; try < method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..); >catch (SecurityException e) < // . >catch (NoSuchMethodException e) < // . >

instead of an integer that you pass to the doSomething , use an array containing name of the methods that you want to call and inside a for loop call each method this way:

Then you invoke that method by calling

try < method.invoke(obj, arg1, arg2. ); >catch (IllegalArgumentException e) < >catch (IllegalAccessException e) < >catch (InvocationTargetException e)  

Unfortunately Java has not delegates!

While I believe this approach will work (as in, it will produce the desired result), reflection is a needlessly complicated solution to this problem, IMO.

@BrianS- Indeed as I already said the most natural way to do this in java is using if statement, however as OP doesn't want it, I tried to do it as close as possible to c# delegates, that is missing in java.

The common Java solution is some variant on the Observer pattern (yshavit's answer is a simplified version). I will admit, though, that several years ago I wrote a class to achieve your solution in a reusable fashion.

This problem could be solved using OOP techniques.

In java it would look like this:

public abstract class AObject < public abstract void doSomething(); public void up()< //do something here >public void down() < //do something here >public void left() < //do something here >public void right() < //do something here >public void stop() < //do something here >> public class AObject12 extends AObject < public void doSomething()< up(); left(); stop(); >> public class AObject304 extends AObject < public void doSomething()< right(); up(); stop(); >> public class AObject962 extends AObject < public void doSomething()< down(); left(); up(); stop(); >> 

Executing doSomething on a instance of a concrete class will trigger the appropriate behavior. So no more if/else is necesary. See code below for an example:

AObject A12 = new AObject12(); A12.doSomething(); // Will run Up left stop in that order AObject A304 = new AObject304(); A304.doSomething(); // Will run right Up stop in that order AObject A962 = new AObject962(); A962.doSomething(); // Will run down left up stop in that order 

Источник

JAVA Else without if? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.

grades.java:18: error: 'else' without 'if' else ^ 1 error 
public class grades < public static void main (String [] args) < int gradeone=75; int gradetwo=80; int testscore= ((gradeone + gradetwo)/2); char grade; System.out.println("\n" + "your test score is" + testscore); if(testscore >= 90 ) grade='A'; elseif(testscore >= 80 ); grade='B'; elseif(testscore >= 70 ); grade='C'; elseif(testscore >= 65 ); grade='D'; else grade='F'; > > 

That's not Java. There's no such thing as elseif . You will want to read the intro tutorial on use of if and else statements. Please check out the link as it will explain all.

Also, for emphasis, please be aware that, while semi-colons immediately after a conditional are legal, it will result in behavior you may not expect - namely, the conditional will be considered 'empty' (ie - if there was a semi-colon immediately after the last else , grade would always be set to 'F'

"elseif" has nothing to do with Java. There are people who try to adopt this notion in Java or C. but its just dangerous construct "else if" without any braces in between. that results in headaches to maintain code

5 Answers 5

As others have already mentioned the syntax is else if - mind the space.

Moreover, I highly recommend you stick to conventional coding style until you become more confident in your skills.

A) For now, use brace syntax when using blocks and statements. Your code will be more readable and you will be able to identify your syntax errors easier. Though technically not required, you will be challenged trying to determine local variables and method scope without braces.

 public static void main( String[] args ) < int gradeOne = 75, gradeTwo = 80, testScore = ( ( gradeOne + gradeTwo ) / 2 ); char grade; if( testScore >= 90 ) < grade = 'A'; >else if( testScore >= 80 ) < grade = 'B'; >else if( testScore >= 70 ) < grade = 'C'; >else if( testScore >= 65 ) < grade = 'D'; >else < grade = 'F'; >System.out.println( "\n" + "your test score is: " + testScore ); > 

B) When your uncertain about the syntax refer to the JLS for answers .

Источник

Use Java lambda instead of 'if else'

I can write a similar ifNotExist , and I want they are mutually exclusive (if the exist condition is true, there is no need to check ifNotExist , because sometimes, the exist() method takes so much workload to check), but I always have to check two times. How can I avoid that? Maybe the "exist" word make someone misunderstand my idea. You can imagine that I also need some methods:

ifVisible() ifEmpty() ifHasAttribute() 

Many people said that this is bad idea, but: In Java 8 we can use lambda forEach instead of a traditional for loop. In programming for and if are two basic flow controls. If we can use lambda for a for loop, why is using lambda for if bad idea?

for (Element element : list) < element.doSomething(); >list.forEach(Element::doSomething); 
Optional element = . element.ifPresent(el -> System.out.println("Present " + el); 

And about code maintenance and readability, what do you think if I have the following code with many repeating simple if clauses?

if (e0.exist()) < e0.actionA(); >else < e0.actionB(); >if (e1.exist()) < e0.actionC(); >if (e2.exist()) < e2.actionD(); >if (e3.exist())
e0.ifExist(Element::actionA).ifNotExist(Element::actionB); e1.ifExist(Element::actionC); e2.ifExist(Element::actionD); e3.ifExist(Element::actionB); 

Which is better? And, oops, do you notice that in the traditional if clause code, there's a mistake in:

Источник

If without else ternary operator

So far from I have been searching through the net, the statement always have if and else condition such as a ? b : c . I would like to know whether the if ternary statement can be used without else . Assuming i have the following code, i wish to close the PreparedStatement if it is not null (I am using Java programming language.)

PreparedStatement pstmt; //. (pstmt!=null) ? pstmt.close : ; 

The ternary operator is not equivalent to if/else. It's actually an expression that has to have a value.

You cannot use ternary without else, but you can use Java 8 Optional class: Optional.ofNullable(pstmt).ifPresent(pstmt::close) . See my answer below.

in place of your just put a variable with a value, like the number 0 or a string, it shouldn't do anything, although it does return a type, or even undefined or a null or void type MIGHT workm but also might cause an error in java

10 Answers 10

Why using ternary operator when you have only one choice?

if (pstmt != null) pstmt.close(); 

It's the exact same length.

As mentioned in the other answers, you can't use a ternary operator to do this.

However, if the need strikes you, you can use Java 8 Optional and lambdas to put this kind of logic into a single statement:

Optional.of(pstmt).ifPresent((p) -> p.close()) 

Ternary if operator is the particular ternary operator. One of a kind.

In mathematics, a ternary operation is an n-ary operation with n = 3.

It means all 3 operands are required for you.

A ternary operation is called ternary beacause it takes 3 arguments, if it takes 2 it is a binary operation.

And as noted above, it is an expression returning a value.

If you omit the else you would have an undefined situation where the expression would not return a value.

So as also noted in other answer, you should use an if statement.

You cannot use ternary without else, but to do a "if-without-else" in one line, you can use Java 8 Optional class.

PreparedStatement pstmt; //. Optional.ofNullable(pstmt).ifPresent(pstmt::close); //  
(pstmt!=null) ? pstmt.close : null; 

is dirty solution but works.

The line of code above translates to When the left side of the expression "translates" to true -> execute the right side.

Well in JavaScript you can simply do:

expression ? doAction() : undefined 

since that's what's literally actually happening in a real if statement, the else clause is simply undefined. I image you can do pretty much the same thing in (almost?) any programming language, for the else clause just put a null-type variable that doesn't return a value, it shouldn't cause any compile errors.

or just make a function to return if all else fails

function oy(x1,x2) oy(etzem==6, ()=>yichoyliss=8); 

Источник

Оцените статью