Java: Convert the number to decimal you can use Integer.parseInt with a single p
ID: 3667475 • Letter: J
Question
Java:
Convert the number to decimal
you can use Integer.parseInt with a single parameter (that is for the default, decimal)
however you are not allowed to call the two parameter version of parseInt that allows you to use radix
for reference, converting from either a character to an int… or a String to an int
Character.getNumericValue(ch) // char to int
ch - 48 // or ch - '0', assuming your character is a digit
Integer.parseInt(s) // string to int, don't use radix for this assignment!
Example Output
Please enter a hex (0x) or binary (0b) number:
>0xFFF1
Converting from base-16 to base-10
65521
Explanation / Answer
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
String digits = "0123456789ABCDEF";
// Console console = System.console();
// String s = console.readLine("Enter input:");
System.out.println("Please enter a hex (0x) or binary (0b) number:");
Scanner scan = new Scanner(System.in);
String s = scan.next();
s = s.toUpperCase();
int val = 0;
if(s.charAt(1) == 'X'){
System.out.println("Converting from base-16 to base-10");
for (int i = 2; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
System.out.println("values =" + val);
}
if(s.charAt(1) == 'B'){
System.out.println("Converting from base-2 to base-10");
for (int i = 2; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 2*val + d;
}
System.out.println("values =" + val);
}
}
}
------------------------
output :
Please enter a hex (0x) or binary (0b) number: 0b1111111111110001
Converting from base-2 to base-10
values =65521
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.