如何为答案为数字的部分添加异常处理?

时间:2014-03-02 00:36:23

标签: java exception-handling

对此非常困惑。 如何为答案为数字的部分添加异常处理? 不知道在哪里添加try和catch。

 do {
//zip code      
     do {
            System.out.println("Enter your zip code(or enter 0 to quit): ");
            zip = input.nextInt();
        } while ((zip > 99999 || zip < 10000) && zip != 0);
        if (zip == 0){
            break;
                    }
                    //age
    do {
            System.out.println("Enter your age: ");
            age = input.nextInt();
    } while (age < 10 || age > 110);


                    //items
     do {
            System.out.println("Enter number of items : ");
            numItems = input.nextInt();
            entries = entries + 1;
            if (entries == 3 && numItems < 1) {
                System.out.println("Invalid. Order was not counted");
                           break;
            }

1 个答案:

答案 0 :(得分:1)

循环直到输入有效数字的粗略方式是要求输入字符串,尝试将其转换为数字,并继续这样做,直到此转换没有失败:< / p>

   import  java.util.Scanner;
/**
   <P>{@code java StringToNumberWithTesting}</P>
 **/
public class StringToNumberWithTesting  {
   public static final void main(String[] ignored)  {

      int num = -1;

      do  {
         nfx2 = null;
         System.out.print("Number please: ");
         String strInput = (new Scanner(System.in)).next();
         try  {
            num = Integer.parseInt(strInput);
         }  catch(NumberFormatException nfx)  {
            nfx2 = nfx;
            System.out.println(strInput + " is not a number. Try again.");
         }
      }  while(nfx2 != null);

      System.out.println("Number: " + num);
   }
}

输出:

[C:\java_code\]java StringToNumberWithErrLoop
Number please: etuh
etuh is not a number. Try again.
Number please: 2
Number: 2

但是使用缺少异常作为逻辑的替代品在现实世界的应用程序中绝不是一个好主意。更好的方法是确认字符串包含一个数字,您可以使用Commons'NumberUtils.isNumber(s)

    import  java.util.Scanner;
    import  org.apache.commons.lang.math.NumberUtils;
 /**
    <P>{@code java StringToNumberWithTesting}</P>
  **/
 public class StringToNumberWithTesting  {
    public static final void main(String[] ignored)  {

       int num = -1;
       boolean isNum = false;

       do  {
          System.out.print("Number please: ");
          String strInput = (new Scanner(System.in)).next();
          if(!NumberUtils.isNumber(strInput))  {
             System.out.println(strInput + " is not a number. Try again.");
          }  else  {
             //Safe to convert
             num = Integer.parseInt(strInput);
             isNum = true;
          }
       }  while(!isNum);

       System.out.println("Number: " + num);
    }
}

输出:

[C:\java_code\]java StringToNumberWithTesting
Number please: uthoeut
uthoeut is not a number. Try again.
Number please: 3
Number: 3

更多信息: How to check if a String is numeric in Java