开发者

How do I validate the input by checking that the input for name is a string and the input for the partId is a long?

开发者 https://www.devze.com 2023-03-22 09:32 出处:网络
static Product createProduct() { Scanner sc = new Scanner(Syste开发者_开发百科m.in); System.out.println(\"\\nEnter new product \");
static Product createProduct() {
        Scanner sc = new Scanner(Syste开发者_开发百科m.in);

        System.out.println("\nEnter new product ");

       System.out.print("  Name: ");
        String n =sc.nextLine();
        while(n==sc.nextLine()){

            if(n !=sc.nextLine()){ 
             System.out.println("ERROR! Please Try again!");
            }
             sc.nextLine();
            }


I'd recommend you to use regular expressions, e.g. read input as strings, then validate that the strings are parsable, then parse.

I do not know what the your requirements for name but I know that long must at least match the following regular expression ^\d+$.

Here is how you can validate your input:

if (Pattern.compile("^\\d+$").matcher(idStr).find()) {
    long id = Long.parseLong(idStr);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消