开发者

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?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜