本文介绍了Hot,可防止在输入String(而不是int)后停止程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当输入String而不是int时,如何防止崩溃?这就是我所拥有的.我尝试查找一些教程,但仍然无法弄清楚.感谢您的帮助.输入字符串时,我需要它告诉用户输入一个整数
How do I stop this from crashing when a String is entered instead of an int?Here is what i have. I've tried looking up some tutorials but I still couldn't figure it out.Thanks for the help guys. When a String is entered i need it to tell the user to enter an 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();
}
}
推荐答案
通过检查InputMismatchException,您可以通知用户他们输入了无效的输入,并且可以要求他们仅重新输入数字.
By checking the InputMismatchException you can inform the users that they have entered an invalid input, and you can ask them to re-enter only Numbers.
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);
}
}
也等于两倍
希望您期待这一件事.如果没有,请评论您的requiremet.
hope you expected this one. if not please kindly comment your requiremet.
这篇关于Hot,可防止在输入String(而不是int)后停止程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!