[Rozwiązany] Formatting And Converting Numbers - Java task

  

4
Rozpoczęcie tematu

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

2 Odpowiedzi
3

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);
    }
}
1

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);
    }
}
Udostępnij: