Skip to content

Commit 0a369b9

Browse files
committed
feat: Implement binary to decimal conversion using Scanner.useRadix(2)
- Prompt user to input a binary number (comprising only 0s and 1s). - Configured Scanner to interpret input using base-2 (`useRadix(2)`). - Used `nextInt()` to parse the binary string into a decimal integer. - Wrapped parsing logic in a try-catch block to handle InputMismatchException. - Displays an appropriate error message if non-binary input is entered. - Used a `finally` block to ensure Scanner resource is properly closed. - Included a comment with an example to explain the binary-to-decimal calculation. Example: Input: 1010 Output: Decimal value: 10 This commit demonstrates robust input handling and introduces a simple yet effective use of Java's radix-based parsing for binary number systems. Signed-off-by: Somesh diwan <[email protected]>
1 parent 84ed62e commit 0a369b9

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import java.util.Scanner;
2+
3+
public class RadixMethod2 {
4+
public static void main(String args[]) throws Exception {
5+
Scanner sc = new Scanner(System.in);
6+
System.out.println("Enter a binary number (using only 0s and 1s):");
7+
sc.useRadix(2);
8+
9+
try {
10+
int x = sc.nextInt();
11+
System.out.println("Decimal value: " + x);
12+
} catch (java.util.InputMismatchException e) {
13+
System.out.println("Error: Please enter a valid binary number (only 0s and 1s allowed)");
14+
} finally {
15+
sc.close();
16+
}
17+
}
18+
}
19+
20+
/* for, example: "1010" in binary = (1×2³) + (0×2²) + (1×2¹) + (0×2⁰) = 8 + 0 + 2 + 0 = 10 in decimal */

0 commit comments

Comments
 (0)