如果我想在输入错误类型的数据类型时抛出异常,我该如何使用IllegalArgumentException执行此操作?
if(row < 1) {
row = 1;
}
if(row > 5) {
row = 5;
}
if (row != int) {
throw new IllegalArgumentException("Please enter appropriate integer.");
}
System.out.print("Specify red value (0-255): ");
int red = console.nextInt();
if(red < 0) {
red = 0;
}
if(red > 255) {
red = 255;
}
if (red != int){
throw new IllegalArgumentException("Please enter appropriate integer.");
}
System.out.print("Specify green value (0-255): ");
int green = console.nextInt();
if(green < 0) {
green = 0;
}
if(green > 255) {
green = 255;
}
if (green != int){
throw new IllegalArgumentException("Please enter appropriate integer.");
}
System.out.print("Specify blue value (0-255): ");
int blue = console.nextInt();
if(blue < 0) {
blue = 0;
}
if(blue > 255) {
blue = 255;
}
if (green != int){
throw new IllegalArgumentException("Please enter appropriate integer.");
}
我的主要问题是&#34;!= int&#34;部分。我知道这是不对的,但我不确定还能用什么。使用else语句也不起作用。如果有人要在扫描程序中输入double,string或boolean输入而不是整数,我怎么能为此抛出异常?我必须为一个赋值执行此操作,并且他们明确表示我需要为此使用throw异常。提前谢谢大家!
答案 0 :(得分:1)
(red != int)
你想做什么
让我来问题标题 "Throwing exception for wrong data types"
。好吧,如果这是实际的问题,那么你不需要做任何行
int red = console.nextInt();
如果数据类型不是整数,将自动抛出异常。
答案 1 :(得分:0)
以新方法为例。
private void inputColorDetails(){
if(row < 1) {
row = 1;
}
if(row > 5) {
row = 5;
}
if (row != int) {
throw new IllegalArgumentException("Please enter appropriate integer.");
}
System.out.print("Specify red value (0-255): ");
int red = console.nextInt();
if(red < 0) {
red = 0;
}
if(red > 255) {
red = 255;
}
if (red != int){
throw new IllegalArgumentException("Please enter appropriate integer.");
}
System.out.print("Specify green value (0-255): ");
int green = console.nextInt();
if(green < 0) {
green = 0;
}
if(green > 255) {
green = 255;
}
if (green != int){
throw new IllegalArgumentException("Please enter appropriate integer.");
}
System.out.print("Specify blue value (0-255): ");
int blue = console.nextInt();
if(blue < 0) {
blue = 0;
}
if(blue > 255) {
blue = 255;
}
if (green != int){
throw new IllegalArgumentException("Please enter appropriate integer.");
}
}
在main中调用它们作为try catch。
private void Main(){
try {
inputColorDetails();
} catch (NumberFormatException e) {
System.out.prinln(e.getMessage());
} }
答案 2 :(得分:-1)
您可以使用“instanceof”关键字或Class.isInstance()
var instanceof Integer
Integer.class.isInstance(var)
正如JB Nizet所指出的那样,nextInt()方法只返回一个整数,因此不需要进行此检查。
要获得任何输入并在之后检查,您可以
int color;
String input = console.next();
try {
color = Integer.parseInt(input)
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Input \"" + input + "\" was not an integer");
}
(代码离我头顶,如果我错了请纠正我)