Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Below is my code to my hex to decimal conversion program. I am unsure of what th

ID: 3628063 • Letter: B

Question


Below is my code to my hex to decimal conversion program. I am unsure of what the user input and output is. I need help with that and how to code a check of the user input where they can only input numbers 0-9 and letters a-f. thanks.

package hextodecimal;

import java.util.Scanner;
public class HexToDecimal {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Scanner input = new Scanner(System.in);

System.out.print("Enter a hex numnber: ");
String hex = input.nextLine();

System.out.println("The decimal value for hex number: " + hex + " is "
+ hexToDecimal(hex.toUpperCase()));
}
public static int hexToDecimal(String hex) {
int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
}
return decimalValue;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') {
return 10 + ch - 'A';
} else // ch is '0','1', ......, or '9'
{
return ch - '0';
}
}//end of main
}//end of class

Explanation / Answer

please rate - thanks

import java.util.Scanner;
public class HexToDecimal {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Scanner input = new Scanner(System.in);

System.out.print("Enter a hex numnber: ");
String hex = input.nextLine();
if(valid(hex))
System.out.println("The decimal value for hex number: " + hex + " is "
+ hexToDecimal(hex.toUpperCase()));
else
     System.out.println("input invalid");
}
public static boolean valid(String hex)
{int i;
for(i=0;i<hex.length();i++)
     if(!(hex.charAt(i)>='a'&&hex.charAt(i)<='f'||hex.charAt(i)>='A'&&hex.charAt(i)<='F'||
        hex.charAt(i)>='0'&&hex.charAt(i)<='9'))
              return false;
return true;
}
public static int hexToDecimal(String hex) {
int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
}
return decimalValue;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') {
return 10 + ch - 'A';
} else // ch is '0','1', ......, or '9'
{
return ch - '0';
}
}//end of main
}//end of class

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote