Advertisement
coasterka

#2FormattingNumbers

May 13th, 2014
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. import java.text.DecimalFormat;
  2. import java.util.Locale;
  3. import java.util.Scanner;
  4.  
  5. public class FormattingNumbers {
  6.     public static void main(String[] args) {
  7.         Locale.setDefault(Locale.ROOT);
  8.         Scanner scan = new Scanner(System.in);
  9.         int a = scan.nextInt();
  10.         if (a < 0) {
  11.             a *= -1;
  12.         }
  13.         double b = scan.nextDouble();
  14.         double c = scan.nextDouble();
  15.        
  16.         //print the first number in hex format
  17.         String hexA = Integer.toHexString(a);
  18.         printVerticalLine();
  19.         System.out.print(hexA.toUpperCase());
  20.         printWhiteSpaces((10 - hexA.length()));
  21.         printVerticalLine();
  22.        
  23.         //print the first number in binary format
  24.         String binB = Integer.toBinaryString(a);
  25.         if (binB.length() < 10) {
  26.             printZeroes((10 - binB.length()));
  27.         }
  28.         System.out.print(binB);
  29.         printVerticalLine();
  30.        
  31.         //print the second number with 2 digits after
  32.         //the decimal point
  33.         DecimalFormat twoDecPoints = new DecimalFormat("#.00");
  34.         String formattedB = twoDecPoints.format(b);
  35.         printWhiteSpaces(10 - formattedB.length());
  36.         System.out.print(formattedB);
  37.         printVerticalLine();
  38.        
  39.         //print the third number with 3 digits after
  40.         //the decimal point
  41.         DecimalFormat threeDecPoints = new DecimalFormat("#.000");
  42.         String cString = Double.toString(c);
  43.         if (c == (int) c) {
  44.             System.out.print((int)c);
  45.         }
  46.         else{
  47.             System.out.print(threeDecPoints.format(c));
  48.         }
  49.     }
  50.  
  51.     private static void printZeroes(int i) {
  52.         for (int j = 0; j < i; j++) {
  53.             System.out.print("0");
  54.         }      
  55.     }
  56.  
  57.     private static void printVerticalLine() {
  58.         System.out.print("|");
  59.     }
  60.  
  61.     private static void printWhiteSpaces(int i) {
  62.         for (int j = 0; j < i; j++) {
  63.             System.out.print(" ");
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement