Below is my code to my hex to decimal conversion program, i need to know where a
ID: 3628064 • Letter: B
Question
Below is my code to my hex to decimal conversion program, i need to know where all i need to change the hex to oct or octal to make it work. it is coded now to check a hex decimal user input, i need that code changed to check only octal as well. so basically i need this entire program converted to check for octal just like it checks for hexidecimal.package hextodecimal;
import java.util.Scanner;
public class HexToDecimal {
/**
* @param args the command line arguments
/**
* @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
Explanation / Answer
please rate - thanks
import java.util.Scanner;
public class OctalToDecimal {
/**
* @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 an octal numnber: ");
String octal = input.nextLine();
if(valid(octal))
System.out.println("The decimal value for octal number: " + octal + " is "
+ octalToDecimal(octal.toUpperCase()));
else
System.out.println("input invalid");
}
public static boolean valid(String octal)
{int i;
for(i=0;i<octal.length();i++)
if(!(octal.charAt(i)>='0'&&octal.charAt(i)<='7'))
return false;
return true;
}
public static int octalToDecimal(String octal) {
int decimalValue = 0;
for (int i = 0; i < octal.length(); i++) {
char octalChar = octal.charAt(i);
decimalValue = decimalValue * 8 + octalCharToDecimal(octalChar);
}
return decimalValue;
}
public static int octalCharToDecimal(char ch) {
return ch - '0';
}
}//end of class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.