Use for loop, while loop, and do while loops to generate a table of decimal numb
ID: 3907884 • Letter: U
Question
Use for loop, while loop, and do while loops to generate a table of decimal numbers as well as the binary, octal, and hexadecimal equivalents of the decimal numbers in the range 1-256 Note: See Appendix for number systems The program should print the results to the Console without using any string formats Design Details The Main program should prompt the user for input The output is shown in the sample output below Note: To generate the binary numbers your code should use a while loop to generate the binary numbers, a "for" loop to generate the octal numbers and a "do.. while" to generate the hexadecimal numbers Sample Output: Enter the low number: Enter the high number: 10 Decimal Binary Octal Hexadecimal 1 1 10 3 100 101 110 7 10 1000 1001 1010 10 12 ****Resetting low and high Low-10, High-15 Octal hexadecimal 12 13 14 15 16 17 Decimal Binary 10 12 13 14 15 1010 1011 1100 1101 1110 Press any key to continue .. .Explanation / Answer
import java.util.Scanner;
public class Conversion
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//Taking input from the user
System.out.println("Enter The Low Number : ");
int inputNumber = sc.nextInt();
System.out.println("Enter The High Number : ");
int inputNumber1 =sc.nextInt();
Conversion c= new Conversion();
System.out.println("Decimal Binary Octal Hexadecimal");
for(int i = inputNumber;i<=inputNumber1;i++){
System.out.println(i+" "+c.binary(i)+" "+c.octal(i)+" "+c.hexadecimal(i));
}
}
public String hexadecimal(int inputNumber){
int copyOfInputNumber = inputNumber;
//Initializing hexa to empty string
String hexa = "";
String octal ="";
//Digits in HexaDecimal Number System
char hexaDecimals[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
//Defining rem to store remainder
int rem = 0;
//See the below explanation to know how this loop works
while (inputNumber > 0)
{
rem = inputNumber%16;
hexa = hexaDecimals[rem] + hexa;
inputNumber = inputNumber/16;
}
return hexa;
}
public String octal(int inputNumber){
int copyOfInputNumber = inputNumber;
//Initializing octal to empty string
String octal = "";
//Defining rem to store remainder
int rem = 0;
//See the below explanation to know how this loop works
while (inputNumber > 0)
{
rem = inputNumber%8;
octal = rem + octal;
inputNumber = inputNumber/8;
}
return octal;
}
public String binary(int inputNumber){
int copyOfInputNumber = inputNumber;
//Initializing binary to empty string
String binary = "";
//Defining rem to store remainder
int rem = 0;
//See the below explanation to know how this loop works
while (inputNumber > 0)
{
rem = inputNumber % 2;
binary = rem + binary;
inputNumber = inputNumber/2;
}
return binary;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.