settingsAccountsettings
Menusettings

Q: Formatting And Converting Numbers - Java task

+6 votes

Write a program that reads 3 numbers:

  • An integer a (0 ≤ a ≤ 500)
  • A floating-point b and
  • A floating-point c

And prints them in 4 virtual columns on the console. Each column should have a width of 10 characters. The number a should be printed in hexadecimal, left aligned; then the number a should be printed in binary form, padded with zeroes, then the number b should be printed with 2 digits after the decimal point, right aligned; the number c should be printed with 3 digits after the decimal point, left aligned.

Examples:

formatting and converting numbers in Java

asked in Java category by user eiorgert
edited by user golearnweb

2 Answers

+2 votes
 
Best answer

Interesting task indeed! You can view these 3 helpful resourses for better understanding of the formatting numbers in Java:

And here's my solution:

import java.util.Scanner;

public class Pr_03_FormattingNumbers {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int a = scanner.nextInt();
        float b = scanner.nextFloat();
        float c = scanner.nextFloat();

        String bitwise = Integer.toBinaryString(a);
        Integer bitwiseInt = Integer.parseInt(bitwise);
        System.out.printf("|%-10X |%010d|%10.2f|%-10.3f|", a, Integer.parseInt(bitwise), b, c);
    }
}
answered by user golearnweb
edited by user golearnweb
+2 votes

Here is another more explainable and clear solution:

import java.util.Scanner;

public class FormattingNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int firstNumber = scanner.nextInt();
        float secondNumber = scanner.nextFloat();
        float thirdNumber = scanner.nextFloat();

        String firstBox = Integer.toHexString(firstNumber).toUpperCase();
        String secondBox = Integer.toBinaryString(firstNumber);
        int secondBoxAsInteger = Integer.parseInt(secondBox);

        System.out.printf("|%-10s|%010d|%10.2f|-10.3f|", firstBox, secondBoxAsInteger, secondNumber, thirdNumber);
    }
}
answered by user richard8502
edited by user golearnweb
...