Write an application that prints a table of the binary, octal, and hexadecimal equivalents of
the decimal numbers in the range 1 through 256. If you are not familiar with these number systems, read Appendix C first. Place the results in a JTextArea with scrolling functionality. Display the JTextArea in a message dialog.
ANS:
the decimal numbers in the range 1 through 256. If you are not familiar with these number systems, read Appendix C first. Place the results in a JTextArea with scrolling functionality. Display the JTextArea in a message dialog.
ANS:
import javax.swing.*; public class NumberSystem { public static void main( String args[] ) { // create a scrolled pane for the output JTextArea outputTextArea = new JTextArea( 15, 35 ); JScrollPane scroller = new JScrollPane( outputTextArea ); outputTextArea.append( "\nDecimal\tBinary\tOctal\tHexadecimal\n" ); // print out binary, octal and hexadecimal representation // for each number for ( int i = 1; i <= 256; i++ ) { int decimal = i; String binary = "", octal = "", hexadecimal = ""; int temp; // get binary representation while ( decimal >= 2 ) { temp = decimal % 2; binary = temp + binary; decimal /= 2; } binary = decimal + binary; decimal = i; // get octal representation while ( decimal >= 8 ) { temp = decimal % 8; octal = temp + octal; decimal /= 8; } octal = decimal + octal; decimal = i; // get hexadecimal representation while ( decimal >= 16 ) { temp = decimal % 16; switch ( temp ) { case 10: hexadecimal = "A" + hexadecimal; break; case 11: hexadecimal = "B" + hexadecimal; break; case 12: hexadecimal = "C" + hexadecimal; break; case 13: hexadecimal = "D" + hexadecimal; break; case 14: hexadecimal = "E" + hexadecimal; break; case 15: hexadecimal = "F" + hexadecimal; break; default: hexadecimal = temp + hexadecimal; break; } decimal /= 16; } switch ( decimal )
{ case 10: hexadecimal = "A" + hexadecimal; break; case 11: hexadecimal = "B" + hexadecimal; break; case 12: hexadecimal = "C" + hexadecimal; break; case 13: hexadecimal = "D" + hexadecimal; break; case 14: hexadecimal = "E" + hexadecimal; break; case 15: hexadecimal = "F" + hexadecimal; break; default: hexadecimal = decimal + hexadecimal; break; } outputTextArea.append( i + "\t" + binary + "\t" + octal + "\t" + hexadecimal + "\n" ); } // show result JOptionPane.showMessageDialog( null, scroller, "Number System", JOptionPane.INFORMATION_MESSAGE ); // terminate the application System.exit( 0 ); } } // end class NumberSystem
Post A Comment:
0 comments: