Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operators in 'else if' statement

I am trying to learn "if else" statements and I am having trouble with the middle 'if else' part of the script.

package practice;
import java.util.Scanner;
public class Practice {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner in = new Scanner(System.in);
    System.out.println("enter a number between 1 and 10 ");
    if (!in.hasNextDouble()) {
        String word = in.next();
        System.err.println(word + " is not a number");
    } else if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
        Double wrongnumber = in.nextDouble();
        System.err.println(wrongnumber + " is not between 1 and 10");
    } else {
        System.out.println("It works!");
    }
       return;

   }

 }

There are no errors but in the 'else if' block I can't get it to print the err "..... not between 1 and 10", whether or not I put a number between 1 and 10 or higher. It also wont print the "it works!" line anymore when I add the 'else if' block. any suggestions would be much appreciated.

like image 630
RevCarl Avatar asked Nov 17 '25 19:11

RevCarl


2 Answers

You are caling in.nextDouble() several times in your if else block, so you get something else every time.

if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
        Double wrongnumber = in.nextDouble();
        System.err.println(wrongnumber + " is not between 1 and 10");
}

convert it to something like

double next = in.nextDouble();
if (!(next > 0) || !(next <= 10)) {
            Double wrongnumber = next;
            System.err.println(wrongnumber + " is not between 1 and 10");
}

To be logically correct you might switch to Integer instead of Double values.

like image 62
NaN Avatar answered Nov 19 '25 09:11

NaN


You call in.hasNextDouble() several times. Each time it scans new number from input so it may cause your issue. You should also consider how you write conditions. I am aware you may just try what's happening there but this kind of condition is hard to read. You can use

(number <= 1) || (number > 10) (remove negations by inverting operators) for example.

like image 42
stanly Avatar answered Nov 19 '25 08:11

stanly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!