THIS IS IN JAVA Use for loop, while loop, and do while loops to generate a table
ID: 3670131 • Letter: T
Question
THIS IS IN JAVA
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.
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.
See Appendix for number systems.
Sample Output:
Enter the low number:
1
Enter the high number:
10
Decimal Binary Octal Hexadecimal
1 1 1 1
2 10 2 2
3 11 3 3
4 100 4 4
5 101 5 5
6 110 6 6
7 111 7 7
8 1000 10 8
9 1001 11 9
10 1010 12 A
****Resetting low and high ****
Low = 10, High = 15
Decimal Binary Octal hexadecimal
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
Press any key to continue . . .
Explanation / Answer
import java.util.Scanner;
public class Convert {
Scanner scan;
int num;
void getVal() {
int low, high,i,j;
System.out.println("Enter the low number:");
scan = new Scanner(System.in);
low = scan.nextInt();
System.out.println("Enter the high number:");
scan = new Scanner(System.in);
high = scan.nextInt();
System.out.println("Decimal Binary Octal Hexadecimal");
for (i=low;i<=high;i++){
System.out.print(i);
num = i;
binary_convert();
oct_convert();
hex_convert();
}
}
void hex_convert() {
String hexa = Integer.toHexString(num);
int i=0;
do {
char letter = hexa.charAt(i);
System.out.print(letter);
i++;
} while (i < hexa.length());
System.out.println("");
}
void oct_convert() {
String oct = Integer.toOctalString(num);
for (int i = 0; i < oct.length(); i++) {
// Get letters with charAt method.
char letter = oct.charAt(i);
System.out.print(letter);
}
System.out.print(" ");
}
void binary_convert() {
System.out.print(" ");
String bin = Integer.toBinaryString(num);
int i=0;
while (i < bin.length()) {
// Get letters with charAt method.
char letter = bin.charAt(i);
System.out.print(letter);
i++;
}
System.out.print(" ");
}
public static void main(String args[]) {
Convert obj = new Convert();
obj.getVal();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.