Lost and Confused Lost and Confused - 6 months ago 8
Java Question

How do I tell an if statement to do something if it's one greater or less than a random other number?

not the exact program but essentially if I have something like

public class WereWolfenstein2D {
public static void main(String[] args){
{Scanner sc = new Scanner(System.in);
Random number = new Random();
int office;
int hitmenlocation;

office = 1+number.nextInt(16);
hitmenlocation = 1+number.nextInt(16);


and then I want to do an if statement saying that if office is one greater or one smaller than hitmenlocation then something should happen, like print a message. How do I type that sort of a comparison statement out?

Answer

if statement saying that if office is one greater or one smaller than hitmenlocation

Directly translated to...

if( (office - hitmenlocation) == 1 || (office - hitmenlocation) == -1) {
    /* do stuff */
}

A cleaner way of doing this is...

if(Math.abs(office - hitmenlocation) == 1) {
    /* do stuff */
}