我遇到了String
到十六进制的惯例的问题。我必须在输入中取String
并将numers转换成两个例如:
输入中的字符串= FFCF6781。
我必须采取FF和转换,然后采取CF和转换等。
我的代码是:
import java.util.Scanner;
/*
* Sample java source code convert hexadecimal to decimal
*/
public class HexToDecimal {
public static void main(String[] args) {
System.out.print("Hexadecimal Input:");
// read the hexadecimal input from the console
Scanner s = new Scanner(System.in);
String inputHex = s.nextLine();
String str = inputHex;
try{
for (int i=0;i<str.length();i++)
inputHex = str.substring (i,i+2);
// actual conversion of hex to decimal
Integer outputDecimal = Integer.parseInt(inputHex, 16);
System.out.println("Decimal Equivalent : "+outputDecimal);
}
catch(NumberFormatException ne){
// Printing a warning message if the input is not a valid hex number
System.out.println("Invalid Input");
}
finally{
s.close();
}
}
}
答案 0 :(得分:2)
有一些事情。
首先,如果要打印每个十六进制数字,则需要扩展for循环。
另外,每次迭代都需要添加2到i
。
如果输入长度不能被2分割,请捕获OutOfBoundsException。
此代码有效:
public static void main(String[] args) {
System.out.print("Hexadecimal Input:");
// read the hexadecimal input from the console
Scanner s = new Scanner(System.in);
String inputHex = s.nextLine();
String str = inputHex;
try {
for (int i = 0; i < str.length() - 1; i+=2) {
inputHex = str.substring(i, i + 2);
// actual conversion of hex to decimal
Integer outputDecimal = Integer.parseInt(inputHex, 16);
System.out.println("Decimal Equivalent : " + outputDecimal);
}
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
// Printing a warning message if the input is not a valid hex number
System.out.println("Invalid Input");
}
finally {
s.close();
}
}