java - Java中的二进制和十六进制负数
问题描述
我有这个程序可以打印出任何基数的数字,但我只是想知道如何让它以二进制或十六进制打印负数。该方法被调用printInt
,当我尝试以二进制打印负数时它只返回 0,并且它StringIndexOutOfBoundsException
为十六进制输入引发异常。这是代码:
import java.util.Scanner;
public class Nums {
public static final String DIGIT_TABLE = "0123456789abcdef";
//prints nums in any base
public static void printInt(long n, int base){
if(n >= base){
printInt(n / base, base);
}
System.out.print(DIGIT_TABLE.charAt((int) (n % base)));
}
//prints n in decimal form
/*public static void printDecimal(long n){
if(n >= 10){
printDecimal(n / 10);
}
System.out.print((char) ('0' + (n%10)) + " ");
}*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter 5 numbers in the following order: 1 long value to see it in decimal form, a long value and a int for the base "
+ "to be represented in and a long and a base for another number ");
long input1 = s.nextLong();
long input2 = s.nextLong();
int input3 = s.nextInt();
long in4 = s.nextLong();
int in5 = s.nextInt();
System.out.println("Prints number in decimal form");
//printDecimal(input1);
System.out.println();
System.out.println("Prints number in binary: ");
printInt(input2, input3);
System.out.println();
System.out.println("Number in hex");
printInt(in4, in5);
}
}
解决方案
在您的方法中添加一条if
语句printInt
来处理负数:
//prints nums in any base
public static void printInt(long n, int base) {
if (n < 0) {
System.out.print('-');
n = -n;
}
if (n >= base) {
printInt(n / base, base);
}
System.out.print(DIGIT_TABLE.charAt((int) (n % base)));
}
此更改的示例会话:
Enter 5 numbers in the following order: 1 long value to see it in decimal form, a long value and a int for the base to be represented in and a long and a base for another number
-314
-314
2
-314
16
Prints number in decimal form
Prints number in binary:
-100111010
Number in hex
-13a
极端情况:这不适用于数字 -9 223 372 036 854 775 808,最小长值,因为 along
不能保存相应的正值。我认为正确的解决方案是输入验证。例如,要求 long 值在 -1 000 000 000 000 000 000 到 1 000 000 000 000 000 000 范围内,并且碱基在 2 到 16 之间。
推荐阅读
- azure-devops - VSTS 扩展任务认证窗口
- mercurial - TortoiseHG 克隆不起作用并验证操作发出警告
- python - 是否可以在 Python 中使用“print”写入剪贴板?
- hyperledger-fabric - 超级账本作曲家休息服务器错误 grep
- javascript - JavaScript 对象中的不同函数声明之间有什么区别(如果有的话)?
- php - Laravel - 在数据透视表中创建其他列是一种好习惯吗?
- python - 在 Python 上使用无头 Selenium Chrome 驱动程序时未加载网页页面
- angular-components - 具有名称绑定的 Angular UpgradeComponent
- c# - 我想在 ARCore 识别出飞机后立即创建一个对象
- python - RuntimeWarning:从未等待协程