我是java新手,正在尝试做这个程序。基本上输入3个数字,它就会计算出立方体的体积。如果输入负数,则会抛出异常,当输入数量超过 3 个时也会抛出异常。如果输入不是数字,我也希望它抛出异常,但我不知道如何将输入存储在变量中,然后检查它是否是字符串并最终抛出异常。有什么建议么?这是我的代码
public class CubeVolume
{
public static void main(String [] args)
{
try
{
// try if there is more than 3 arguments
int width = Integer.parseInt(args[0]);
int depth = Integer.parseInt(args[1]);
int hight = Integer.parseInt(args[2]);
if (args.length > 3)
throw new ArrayIndexOutOfBoundsException
("You have supplied " + args.length + " arguments!");
// try if there is less than 3 arguments
if (args.length < 3)
throw new ArrayIndexOutOfBoundsException
("You have supplied " + args.length + " arguments!");
// checks if the width entered is equal or less than 0
if (width <= 0)
throw new NumberFormatException
("The argument " + width + " is a negative number!");
// checks if the depth entered is equal or less than 0
if (depth <= 0)
throw new NumberFormatException
("The argument " + depth + " is a negative number!");
// checks if the hight entered is equal or less than 0
if (hight <= 0)
throw new NumberFormatException
("The argument " + hight + " is a negative number!");
int volume = width * depth * hight;
System.out.println("The volume of a cube with dimensions " + "(" + width
+ "," + hight + "," + depth + ") " + "is " + volume);
} // try
// if there's one than more argument error will be displayed
catch (ArrayIndexOutOfBoundsException exception)
{
System.out.println("Please supply width, depth and hight arguments!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch
// if a negative number is entered error will be displayed
catch (NumberFormatException exception)
{
System.out.println("Dimensions for a cube can't be negative, please "
+ "insert only positive whole numbers!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch
} // main
} // CubeMain
最佳答案
这个:
int width = Integer.parseInt(args[0]);
如果相关字符串不是整数的有效字符串表示形式,则已抛出 NumberFormatException。
编辑:
解决您的意见:
public class CubeVolume {
private int width;
private int depth;
private int height;
public static void main(String [] args) {
if (args.length != 3) {
throw new Exception("Width, height and depth are required arguments");
}
width = Integer.parseInt(args[0]);
depth = Integer.parseInt(args[1]);
height = Integer.parseInt(args[2]);
// more stuff here
}
}
关于java - 将字符串识别为输入,如果不是整数则抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22026301/