我无法让我的程序响应空输入.例如,假设我想提示用户输入货币类型BigDecimal以及货币类型.这是有问题的程序的样子.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of money "
+ "and specify currency (USD or CNY): ");
// initialize variable moneyInput
BigDecimal moneyInput;
// check if moneyInput is numeric
try {
moneyInput = input.nextBigDecimal();
} catch (InputMismatchException e){
System.err.println("InputMismatchException: non-numeric value");
return;
}
// specify currency of moneyInput
String currencyType = input.next();
...
}
Run Code Online (Sandbox Code Playgroud)
所以在这里,输入像100.00 USD,工作正常.
Enter the amount of money and specify currency (USD or CNY): …Run Code Online (Sandbox Code Playgroud) 我很困惑为什么如果你想在堆栈上分配 8 字节存储,你使用以下命令
subq $8,%rsp
Run Code Online (Sandbox Code Playgroud)
%rsp 存储一个地址。为什么从 %rsp 中存储的地址中减去文字值 8 会分配 8 个字节?特别是,为什么$x对应x个字节?
编辑:我的问题在此stackoverflow 回复中得到了解答。它以字节为单位,因为这是 int 的大小,而 int 是传入的文字参数。
编辑2:以上是不正确的。参见博的评论。
在分配大尺寸的动态数组时,我遇到了段错误.
作为一个具体示例,以下代码会导致段错误.
int max = 1399469912;
int *arr = (int*) malloc((max+1) * sizeof(int));
arr[0] = 1;
Run Code Online (Sandbox Code Playgroud)
但是,如果我用5之类的小东西替换max,那么我就不会遇到段错误.
为什么会这样?或者,是否有其他解决方案可以达到同样的效果?我需要一个动态分配的大小数组.
谢谢