如何验证这些输入?

时间:2017-04-23 06:13:20

标签: java validation input

我编写了一个简单的程序。它从用户获取两个整数,并将奇数返回给user.i验证它们以强制用户只输入整数。 当用户输入其他数据类型时,程序会给他我的自定义错误。这一直到现在,但是当发生这种情况时,用户必须从头开始输入输入。这意味着程序将用户带到第一个家。 这是我的主要课程:

package train;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Calculate cal = new Calculate();
        Scanner input = new Scanner(System.in);
        int number1 = 0;
        int number2 = 0;
        boolean isNumber;

        do {
            System.out.println("enter number1 please : ");
            if (input.hasNextInt()) {
                number1 = input.nextInt();
                isNumber = true;
                System.out.println("enter number2 please : ");
            }
            if (input.hasNextInt()) {
                number2 = input.nextInt();
                isNumber = true;

            } else {
                System.out.println("wrong number!");
                isNumber = false;
                input.next();
            }

        } while (!(isNumber));

        cal.setNumbers(number1, number2);
        cal.result();
        input.close();
    }
}

这是我的计算类,它返回奇数:

public class Calculate {

    private int minNumber;
    private int MaxNumber;

    public void setNumbers(int min, int max) {
        this.minNumber = min;
        this.MaxNumber = max;
    }

    public void result() {
        int count = 0; // number of results
        ArrayList<Integer> oddNumber = new ArrayList<Integer>(); // array of odd numbers

        // get odd numbers
        for (int i = minNumber; i < MaxNumber; i++) {

            if ((i % 2) != 0) {
                oddNumber.add(i);
                count++;
            }
        }

        int i = 0;// counter for printing array
        while (i < oddNumber.size()) {
            if(i != oddNumber.size()){
                System.out.print(oddNumber.get(i) + ",");
            }else{
                System.out.println(oddNumber.get(i));
            }
            i++;
        }

        // print result numbers
        System.out.println("\nResult number : " + count);

        // print number range
        System.out.println("You wanted us to search between " + minNumber
            + " and " + MaxNumber);

    }

}

2 个答案:

答案 0 :(得分:0)

您可以计算用户输入的Integer输入数量,以及解决问题的方式。

因此您可以将代码修改为:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Calculate cal = new Calculate();
        Scanner input = new Scanner(System.in);
        int number1 = 0;
        int number2 = 0;
        boolean isNumber;
        int totalEnteredNumbers=0;
        int currNumber=1;
        do {
            System.out.println("enter number"+currNumber+" please : ");
            if (totalEnteredNumbers==0 && input.hasNextInt()) {
                number1 = input.nextInt();
                isNumber = true;
                currNumber++;
                System.out.println("enter number"+currNumber+" please : ");
                totalEnteredNumbers++;
            }
            if (totalEnteredNumbers==1 && input.hasNextInt()) {
                number2 = input.nextInt();
                isNumber = true;

            } else {
                System.out.println("wrong number!");
                isNumber = false;
                input.next();
            }

        } while (!(isNumber));

        cal.setNumbers(number1, number2);
        cal.result();
        input.close();
    }
}

无论如何,您也可以将boolean变量isNumber从终止条件中移除,方法是将其替换为while(totalEnteredNumbers<2);

但是,这也可以通过以下代码解决:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Calculate cal = new Calculate();
        Scanner input = new Scanner(System.in);
        int number1 = 0;
        int number2 = 0;

        boolean numberTaken=false;

        while(!numberTaken)
        {
            System.out.print("Enter number1 : ");
            String ip=input.next();
            try
            {
                number1=Integer.parseInt(ip); //If it is not valid number, It will throw an Exception
                numberTaken=true;
            }
            catch(Exception e)
            {
                System.out.println("Wrong Number!");
            }
        }

        numberTaken=false; //For second input

        while(!numberTaken)
        {
            System.out.print("Enter number2 : ");
            String ip=input.next();
            try
            {
                number2=Integer.parseInt(ip); //If it is not valid number, It will throw an Exception
                numberTaken=true;
            }
            catch(Exception e)
            {
                System.out.println("Wrong Number!");
            }
        }
        cal.setNumbers(number1, number2);
        cal.result();
        input.close();
    }
}

答案 1 :(得分:0)

创建方法verifyAndGetNumber,该方法将使用正则表达式\d+验证数字,这意味着匹配一个或多个数字。如果不是数字则抛出异常。捕获异常并打印自定义消息。

public static void main(String[] args) {
    Calculate cal = new Calculate();
    Scanner input = new Scanner(System.in);
    int number1 = 0;
    int number2 = 0;
    boolean isNumber = false;

    do {
        try {
            System.out.println("enter number1 please : ");
            if (input.hasNextLine()) {
                number1 = verifyAndGetNumber(input.nextLine());
            }

            System.out.println("enter number2 please : ");
            if (input.hasNextLine()) {
                number2 = verifyAndGetNumber(input.nextLine());
            }

            isNumber = true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    } while (!isNumber);

    cal.setNumbers(number1, number2);
    cal.result();
    input.close();
}

private static int verifyAndGetNumber(String line) throws Exception {
    if (line.matches("\\d+")) {
        return Integer.parseInt(line);
    }
    throw new Exception("wrong number!");
}