当输入String而不是int时,如何阻止此崩溃? 这就是我所拥有的。我已经尝试查找一些教程,但我仍然无法弄明白。 谢谢你的帮助。当输入String时,我需要它告诉用户输入int
import java.util.Scanner;
public class TaxCalc
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
int dependents = inputInt("Enter number of dependents: ", keyboard);
int pigs = inputInt("Enter number of pigs: ", keyboard);
double oinks= inputInt("Enter number of oinks: ", keyboard) -(pigs*500)+(200*dependents);
System.out.println("Oinks after rewards: " + oinks);
if(oinks<10000) oinks -= oinks*0.02; //2% tax
else if(oinks<5000) oinks -= oinks*0.1; //10% tax
else oinks -= oinks*0.2; //20% tax
System.out.println("Oinks after penalties: " + oinks);
}
public static int inputInt(String prompt, Scanner keyboard){
System.out.println(prompt);
return keyboard.nextInt();
}
public double inputDouble(String prompt, Scanner keyboard){
System.out.println(prompt);
return keyboard.nextDouble();
}
}
答案 0 :(得分:2)
通过检查InputMismatchException,您可以通知用户他们输入了无效输入,您可以要求他们仅重新输入数字。
public static int inputInt(String prompt, Scanner keyboard) {
System.out.print(prompt);
try{
return keyboard.nextInt();
} catch (InputMismatchException e){
System.out.println("Input Mismatch! Please enter Numbers");
keyboard.next();
return inputInt(prompt, keyboard);
}
}
同样适用于双
希望你期待这一个。如果没有请请评论您的要求。
答案 1 :(得分:0)
使用
try
{
// Code here
}
catch (Exception e)
{
// Do anything in case of error
}
答案 2 :(得分:0)
http://www.tutorialspoint.com/java/java_exceptions.htm
这个网站展示了如何在Java上进行异常处理, 基本上做像
这样的事情try {
int dependents = inputInt("Enter number of dependents: ", keyboard);
}
catch(Exception e) {
//do something because an error occured
}
答案 3 :(得分:0)
Nonono,如果可以避免,请不要使用异常(至少不存在Exception,因为存在NumberFormatException)。
如果您想确保只输入数字,请使用
public double inputDouble(String prompt, Scanner keyboard){
try {
while (!keyboard.hasNextInt()) keyboard.next();
return keyboard.nextInt();
} catch (NumberFormatException e) {
return 0; //not a numeric at all.
}
}
答案 4 :(得分:0)
我认为,它适合你。
public static int inputInt(String prompt, Scanner keyboard){
System.out.println(prompt);
if(keyboard.hasNextInt())
return keyboard.nextInt();
else {
System.out.println("please input a number");
keyboard.next();
return inputInt(prompt,keyboard);
}
}