gpt4 book ai didi

java - 使用 args 数组时出现 OutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 07:03:43 25 4
gpt4 key购买 nike

我正在处理一项作业,但不允许我使用扫描仪。相反,我们必须使用 int money = Integer.parseInt(args[0]) 。我尝试编写代码并进行编译,但出现运行时错误,我想知道是否有人可以告诉我我做错了什么以使我走上正确的轨道!

这是我的代码:

class MakingChange {
public static void main(String[] args) {
int money = Integer.parseInt(args[0]);
int toonies = (money / 200);
System.out.println(toonies);
}
}

错误是

java.lang.ArrayIndexOutOfBoundsException: 0
at Money.main(Money.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

我不知道该如何处理这个错误!任何帮助将不胜感激

最佳答案

你应该编写防御性代码,试试这个:

if(args.length>0){
int money = Integer.parseInt(args[0]);
int toonies = (money / 200);
System.out.println(toonies);
}else{
System.out.println("Missing Command Line Arguments");
}

关于java - 使用 args 数组时出现 OutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32802915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com