java 中判断输入是否合法 if (变量名.hasNextInt())

  		//案例:
        Scanner sc = new Scanner(System.in);
        System.out.println("你选择了新修改商品功能!");
        System.out.println("请输入要修改的商品编号:");

        //判断用户输入是否合法:
        if (sc.hasNextInt()){
            //获取用户输入的id,用Integer.parseInt转换类型
            int  id = Integer.parseInt(sc.nextLine());

            //2.查询数据库,如果有告诉用户选择的商品
            ProductService service = new ProductService();
            Product p =  service.findById(id);
            if(p == null){
                System.out.println("商品编号:"+id+"不存在:");
            }else{
                System.out.println("当前选择修改的数据是:");
                System.out.println(p);

                System.out.println("请输入新的商品名字:");
                String newName = sc.nextLine();

                System.out.println("请输入新的商品价格:");
                int newPrice = Integer.parseInt(sc.nextLine());

                //封装商品信息
                p.setProduct_name(newName);
                p.setPrice(newPrice);
                service.editProduct(p);
                System.out.println("修改商品成功!");
            }
        }else{
            System.out.println("输入类型错误错误,请重新输入!");
        }
posted @ 2022-03-06 01:33  千寻简  阅读(114)  评论(0编辑  收藏  举报