ITEC1011 Fall 2000

Assignment 5 Solution

Solutions for Dec2Hex. Dec2Oct is similar
 

import java.io.*;

public class Dec2Hex
{
 private static final int BASE = 16;
        // Dec2Oct is similar: just change BASE to 8.

 public static void main (String[] args) throws NumberFormatException
 {
  // TODO: Add initialization code here
  BufferedReader stdin =
                        new BufferedReader( new InputStreamReader( System.in ), 1  );
  String converted = "";

  try
  {
   System.out.print( "Please Enter a Nonnegative Integer: " );
   int quotient = Integer.parseInt( stdin.readLine());
   if( quotient < 0 )
   {
    throw new NumberFormatException();
   }
   else
   {
    while( quotient > 0 )
    {
     int remainder = quotient % BASE;
     quotient /= BASE;
 
     converted = int2String( remainder )
                                                        + converted;
    }
   }
   System.out.println( converted );
  }
  catch( NumberFormatException e )
  {
   System.out.println( "Please enter a nonnegative integer!" );
  }
  catch( Exception e )
  {
   System.out.println( "Please enter a nonnegative integer!" );
  }
 }

 private static String int2String( int n )
 {
   // there is also a Integer class method that does the conversion
   // but we really prefer them to use the switch
  String s = "";
  switch( n )
  {
  case 0:
   s = "0";
   break;
  case 1:
   s = "1";
   break;
  case 2:
   s = "2";
   break;
  case 3:
   s = "3";
   break;
  case 4:
   s = "4";
   break;
  case 5:
   s = "5";
   break;
  case 6:
   s = "6";
   break;
  case 7:
   s = "7";
   break;
  case 8:
   s = "8";
   break;
  case 9:
   s = "9";
   break;
  case 10:
   s = "A";
   break;
  case 11:
   s = "B";
   break;
  case 12:
   s = "C";
   break;
  case 13:
   s = "D";
   break;
  case 14:
   s = "E";
   break;
  case 15:
   s = "F";
   break;
  }
  return s;
 }
}