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