Do not use if statement in Java

This is a very strange and rather specific question.

I end up trying to write a program converter that accepts a java source and converts it so that it doesn't use (by the way)

  • Arrays
  • Loops
  • User Defined Methods
  • If statements

This is the difficulty that I set for myself after my teacher told me that it is impossible to write a program without using these things.

I have most of them, including the inlining function and array expansion, however I cannot decide how to control the if statement.

In C ++, I would use labels and gotos and maybe?:, However Java does not support GOTO statements.

My question is this: Given a section of code,

if(CONDITION)
{
   //More code in here
}

, , if. , .

, else else if statements. , , , GOTO, .

: , ( - , , ) ?: . AFAIK void ?: .

IB Computer Science SL, , HL, "" SL, "if" ( 3/15 " ). , - SL, , .

: (By bdares)

String result = (CONDITION)?"0":"A";
try{
    Integer.parseInt(result);
    //Condition is true
} catch(NumberFormatException e){
    //Condition is false
}
+5
5
if(A) {
    X();
}
else{
    Y();
}

:

A?X():Y();

, , : if. .

, , :

String result = A?"0":"A";
try{
    Integer.parseInt(result);
    X();
} catch(NumberFormatException e){
    Y();
}
+2

:

switch( CONDITION ? 1 : 0 )
{
    case 1:
        //... true code
        break;
    case 0:
        //... false code
        break;
}

, , . break Java, .

Java goto, , , , JVM , Java-, ifs .

+2

, if. , , , , - if. :

public interface Moveable {
  void move(int x, int y);
}

public class Ball implements Moveable {
  private int x;
  private int y;

  public void move(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

public class NullMoveable {
  public void move(int x, int y) {
    // Do nothing.
  }
}

... :

Moveable mv = new NullMoveable();    
// Move object; don't care if it a Ball or a NullMoveable
// so no need to explicitly check with an if-statement.
mv.move(10, 50);

, (- if), .

+1

-. :

if(x > 0) // positive number
{
    isPositive = true;
}
else // negative number
{
    isPositive = flase;
}

:

isPositive = (x >> 31) == 0;

EDIT:

, , , if.

0

(, , , ):

if(COND) {
  X();
} else {
  Y();
}

:

ifReplacement(COND, 
              new Runnable() { public void run() { X();}},
              new Runnable() { public void run() { Y();}});

:

public static void ifReplacement(boolean condition,
                                 Runnable ifBranch,
                                 Runnable elseBranch)

, Lambdas JDK8 :

ifReplacement(COND, ()->X(), ()->Y());
0

All Articles