Write a program that user enters 4 position hexadecimal number (0-9 and A,B,C,D,
ID: 3775405 • Letter: W
Question
Write a program that user enters 4 position hexadecimal number (0-9 and A,B,C,D,E,F) as “character string” and you print the decimal value along with entered hexadecimal value. ALSO write out pseudocode to solve problem.
HINT: use for loop and switch statement – where switch is based on character . Also rememberMath.pow(a,b) where a is multiplied by itelf b times.
Example “1A2F” =
1 *16*16*16 + 10*16*16 + 2*16 + 15*1
extra credit - expand it so you can enter any length hexadeciamal
Im supposed to use loops and switch statement .
This is what i have so far, but I'm stuck at this point , the thing is i dont really know how to use the loops for this case, I feel it would make things easier, thanks.
import java.util.Scanner;
public class Hex {
public static void main(String[] args) {
Scanner data =new Scanner(System.in);
System.out.print( " enter hexidecimal number ");
String hex = data.next();
int total =0 ;
char hex1 = hex.charAt(0);
switch (hex1 ){
case 'a' :
System.out.println(10*1);
break;
case 'b':
System.out.println(11*1);
break;
case 'c' :
System.out.println(12*1);
break;
case 'd' :
System.out.println(13*1);
break;
case 'e' :
System.out.println(14*1);
break;
case 'f' :
System.out.println(15*1);
break;
}
System.out.println(hex + " is " + hex1 + "in decimal" );
data.close();
}
Explanation / Answer
import java.util.Scanner;
public class Hex {
public static void main(String[] args) {
Scanner data = new Scanner(System.in);
System.out.print(" enter hexidecimal number ");
String hex = data.next();
int total = 0;
hexToDecimal(hex);
data.close();
}
/**
* method to print decimal number equilant to hexadecimal number
*
* @param hexadecimal
*/
public static void hexToDecimal(String hexadecimal) {
int h = hexadecimal.length() - 1;
int d = 0;
int n = 0;
for (int i = 0; i < hexadecimal.length(); i++) {
char ch = hexadecimal.charAt(i);
boolean flag = false;
switch (ch) {
case '1':
n = 1;
break;
case '2':
n = 2;
break;
case '3':
n = 3;
break;
case '4':
n = 4;
break;
case '5':
n = 5;
break;
case '6':
n = 6;
break;
case '7':
n = 7;
break;
case '8':
n = 8;
break;
case '9':
n = 9;
break;
case 'A':
n = 10;
break;
case 'B':
n = 11;
break;
case 'C':
n = 12;
break;
case 'D':
n = 13;
break;
case 'E':
n = 14;
break;
case 'F':
n = 15;
break;
default:
flag = true;
}
if (flag) {
System.out.println("Wrong Entry");
break;
}
d = (int) (n * (Math.pow(16, h))) + (int) d;
h--;
}
System.out.println(hexadecimal + " is " + d + " in decimal");
}
}
OUTPUT:
enter hexidecimal number 1A2F
1A2F is 6703 in decimal
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.