107k views
2 votes
Write a program in Java to read in a non-negative integer less than 128 and print out the binary representation. Use a method header like this: public static String intToBin(int x)

* Ok so I need to be able to read in an integer and print out the binary representation as a string.

*Also need a loop that does this.....example 18%2 = 0 18/2=9 9%2=1 9/2=4 4%2=0 4/2=2 2%2=0 2/2=1 ect..

1 Answer

4 votes

Answer:

Here is code in java.

import java.util.*;

import java.lang.*;

import java.io.*;

class Main

{

//main method of the class

public static void main (String[] args)

{

try{

int num;

//scanner object to read input

Scanner in = new Scanner(System.in);

System.out.print("Enter an integer value between 128 and 0: ");

num = in.nextInt();

//input validation

while(true)

{

if(num < 0)

System.out.println("Number must be a positive value less than 128.");

else if(num >= 128)

System.out.println("Number must be less than 128 and should be a positive value.");

else

break;

System.out.print("\\Enter the number again: ");

num = in.nextInt();

}

// calling function to convert number into binary

System.out.println(intToBin(num));

}catch(Exception ex){

return;}

}

//function to convert number into binary

public static String intToBin(int x)

{

//create an empty string

String binary="";

// convert number to binary

while(x!=0)

{

if(x%2==0)

{

binary="0"+binary;

}

else

binary="1"+binary;

x=x/2;

}

return binary;

}

}

Step-by-step explanation:

First read the input number from user. If number is less than 0 then it will ask again to enter the positive number less than 128. if the number is greater than 128 then it will again ask to enter a number less than 128. After the valid input it will call the function intToBin() with parameter x. Then it will convert the number into binary string and return that string.

Output:

Enter an integer value between 128 and 0: -2

Number must be a positive value less than 128.

Enter the number again: 130

Number must be less than 128 and should be a positive value.

Enter the number again: 83

1010011

User Ibn Rushd
by
7.2k points