4
28/10/2024 7:18 pm
Emne starter
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:
2 Svar
3
28/10/2024 7:19 pm
Interesting task indeed! You can view these 3 helpful resourses for better understanding of the formatting numbers in Java:
- http://alvinalexander.com/programming/printf-format-cheat-sheet (printf format cheatsheet)
- https://www.cs.colostate.edu/~cs160/.Spring16/resources/Java_printf_method_quick_reference.pdf
- https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
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
28/10/2024 7:20 pm
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); } }