Reputation: 31
How can I use If
to check the input must be integer and can't type any english words.
int numWeight = sc.nextInt();
if (numWeight == (int)numWeight) {
((Salad)menu[itemNum - 1]).setWeight(numWeight);
System.out.println(menu[itemNum - 1].showOrderDetails());
System.out.println("-------------------------------------------");
System.out.println("Total No. of items ordered :");
orderedItem[TtlOrderNum] = menu[itemNum - 1];
TtlOrderNum += 1;
Continue();
}
else {
System.out.println("input must a be integer");
}
When I use this code to run it and type integer, it shows:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at SaladAndDrinkOrderSystem.placeOrder(SaladAndDrinkOrderSystem.java:69)
at TestSaladAndDrinkOrderSystem.main(TestSaladAndDrinkOrderSystem.java:23)
Upvotes: 2
Views: 268
Reputation: 327
Note that if you pass a non Integer
value to your numWeight
you will raise an input missmatch exception cannot convert from xxxx to int
, so in my opinion you could use a try-catch assuming you will receive an int and if you do not receive it the catch prints to you that it must be an Integer, something like this:
int numWeight;
try {
numWeight = sc.nextInt();
((Salad)menu[itemNum - 1]).setWeight(numWeight);
System.out.println(menu[itemNum - 1].showOrderDetails());
System.out.println("-------------------------------------------");
System.out.println("Total No. of items ordered :");
orderedItem[TtlOrderNum] = menu[itemNum - 1];
TtlOrderNum += 1;
Continue();
}
catch(InputMismatchException e) {
System.err.println("Input must be an Integer");
}
this way if the sc.nextInt()
do not be an Integer you will print the error saying that it sould be.
But, if you want to keep with your original idea of check is the value is an Integer, you could use instaceof
operator, something like this
Integer numWeight = sc.nextInt();
if (numWeight instanceof Integer) {
((Salad)menu[itemNum - 1]).setWeight(numWeight);
System.out.println(menu[itemNum - 1].showOrderDetails());
System.out.println("-------------------------------------------");
System.out.println("Total No. of items ordered :");
orderedItem[TtlOrderNum] = menu[itemNum - 1];
TtlOrderNum += 1;
Continue();
}
else {
System.out.println("input must a be integer");
}
Remember that if you choose for the second approach you will raise an exception if the st.nextInt()
not be an int.
Upvotes: 0
Reputation: 584
You need to do something like:
int numweight;
try {
numweight = sc.nextInt();
// Rest of your code here...
} catch (InputMismatchException e) {
System.err.println("Please enter an integer");
}
In order to not have java throw an input mismatch exception.
Upvotes: 1