-3

我正在尝试使用tryand catch。如果输入的输入无效,则循环会重复并再次要求用户输入,但它不起作用。当我输入错误时,它只会重复System.out.println.

import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class Price
{
    public static void main(String[] args)
    {
        userInput();
    }
    public static void userInput()
    {
        Scanner scan = new Scanner(System.in);
        int x = 1;
        int month, day, year;

        do {
            try {    
                System.out.println("Please enter a month MM: ");
                month = scan.nextInt();

                if(month>12 && month<1)
                {
                    System.out.println("FLOP");
                } 
                x=2;
            }
            catch(Exception e){
                System.out.println("not today mate");
            }
        }
        while(x==1);             
    }
}
4

3 回答 3

0

作为一般规则,异常用于异常情况,而不是驱动程序的逻辑。在这种情况下,验证输入的数据并不是例外情况。用户可能会出错并输入错误的数字是正常的情况。将输入放入一个循环中并重复,直到输入正确的值(也许用户可以选择取消)。

于 2013-03-22T01:23:14.273 回答
0

首先你的条件不对。

你有:

if(month>12 && month<1)
{
  System.out.println("FLOP");
}

所以月份不能大于 12 并且同时小于 1。

I think you wanted to put OR instead of AND, e.g.

if(month > 12 || month < 1)
{
  System.out.println("FLOP");
}

As for the exception, it might occur when user enters non numeric value or input is exausted. Throws: InputMismatchException - if the next token does not match the Integer regular expression, or is out of range NoSuchElementException - if input is exhausted IllegalStateException - if this scanner is closed

于 2013-03-22T01:42:35.413 回答
0

this is a working solution to your problem

public static void userInput(){
        Scanner scan = new Scanner(System.in);
        int x = 1;
        int month, day, year;

        System.out.println("Please enter a month MM: ");
        month = scan.nextInt();
        boolean i = true;
        while(i == true)
        {
            if(month < 12 && month > 1)
            {
                System.out.println("FLOP");
                i = false;
            }
            else if(month >= 12 || month <= 1)
            {
                System.out.println("not today mate");
                month = scan.nextInt();                
            }
        }     

  }
于 2013-03-22T01:50:56.973 回答