Home > Software design >  find binary equivalent of integer in java using while loop
find binary equivalent of integer in java using while loop

Time:03-01

I'm new in JAVA. I've been writing code on finding binary equivalent of integer in java using while loop. I've written the following code and it's not throwing any error but it was not printing INVALID INPUT. But it is printing valid binary number of given integer value. Can anyone suggest where and what I'm doing wrong? And how Should I get the proper input.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if (!(n >= 0) && n > 999) {
            System.out.println("Invalid Input");
        } else {
            while (n > 1) {
                if (n <= 999) {
                    System.out.println(Integer.toBinaryString(n));
                    break;
                }
            }


        }
    }
}

CodePudding user response:

Change && to ||:

if (!(n >= 0) || n > 999) {

Or even better, express conditions without negation:

if (n < 0 || n > 999) { 

Positive conditions, ie "a is b", are easier to read.

CodePudding user response:

Why are you using a loop at all? You're just adding needless complexity. Your code can be re-written to this:

if (n >= 0 && n < 1000) {
   System.out.println(Integer.toBinaryString(n));
   return;
}
    
System.out.println("Invalid Input");
  •  Tags:  
  • java
  • Related