热从进入一个int之后的字符串是不是崩溃停止程序(Hot to stop the program f

2019-10-21 03:04发布

如何从当输入的字符串代替int的崩溃停止? 这里是我有。 我试着仰视一些教程,但我仍然无法弄清楚。 感谢您的帮助球员。 当输入一个字符串,我需要它来告诉用户输入一个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();
    }
}

Answer 1:

通过检查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);
        }
}

同为双也

希望你预计今年之一。 如果不请您评论您requiremet。



Answer 2:

采用

try
{
  // Code here 
}
catch (Exception e)
{
  // Do anything in case of error
}


Answer 3:

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
}


Answer 4:

NONONO,不使用异常(至少不会例外,因为有一个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. 
  }
}


Answer 5:

我想,这与您合作。

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);
    }
}


文章来源: Hot to stop the program from crashing after a String is entered instead of an int
标签: java jgrasp