这是我正在编写的代码。问题是当我输入非十六进制值(例如“rr”或“z”)时,它会打印负值。我怎样才能阻止它这样做?另外,我该如何解决这个问题?当程序启动时,它会要求用户输入长度为 2 的十六进制数(例如 1F)。用户应输入的最小数字是 90(十进制相当于 144),最大数字是 FF(十进制相当于 255)。
import java.util.Scanner;
public class HexaConverter {
public static int hex2decimal(String s)
{
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
//Start of conversion method
public static void main(String args[])
{
String hexadec_num;
int dec_num, i=1, j;
int bin_num[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a Hexadecimal Number: ");
hexadec_num = scan.nextLine();
final int MAX_LENGTH = 2;
if(String.valueOf(hexadec_num).length() <= MAX_LENGTH) {
/* first convert the hexadecimal to decimal */
dec_num = hex2decimal(hexadec_num);
System.out.print("Equivalent Dec Number is : "+ dec_num);
System.out.println();
/* now convert the decimal to binary */
while(dec_num != 0)
{
bin_num[i++] = dec_num%2;
dec_num = dec_num/2;
}
System.out.print("Equivalent Binary Number is : ");
System.out.print("\n");
for(j=i-1; j>0; j--)
{
System.out.print(bin_num[j]);
}
}
else
{
System.out.println("ERROR: Input number was too long");
main(args); // calling to return to the main method
}
}
}
最佳答案
int d =digits.indexOf(c);
如果数字字符串中不存在该字符,如果您添加对此的检查:
int d = digits.indexOf(c);
if (d == -1) return 0; // CHECK HERE
val = 16*val + d;
然后你可以按照你喜欢的方式处理错误,在这个例子中我只是返回0
对于问题的第二部分,您只需检查返回结果的值是否在144和255范围内即可
if (144 <= dec_num && dec_num <= 255) return "SUCCESS";
return "FAIL";
关于java - 如何防止代码打印负输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60567757/