Java聚合类场景下用户输入存入ArrayList时构造方法参数不匹配问题求解
问题原因
- 参数数量不匹配:你定义的
treatment类构造方法仅接收3个入参,依次为String treatment_type、String treatment_procedure、booking bookings,调用时你传入了6个String参数,数量不匹配触发第一次报错。 - 参数类型与顺序错误:你尝试传3个参数时,直接将患者姓名、就诊日期这类String类型变量传入了要求
booking类型的参数位,触发类型转换报错;同时你搞错了treatment构造方法的入参顺序,前两个参数是诊疗类信息,患者、医生、预约时间都属于booking类的属性,不能直接传给treatment的构造。
解决方法
你需要先把收集到的患者名、医生名、预约日期、预约时间四个参数实例化为booking对象,再按treatment构造方法要求的参数顺序传入即可,修正后的驱动类代码如下:
public static void treatments(){ Scanner sc = new Scanner(System.in); System.out.println("Please provide treatment information"); System.out.println("Enter the Patient's name :"); String pname = sc.next(); System.out.println("Enter the doctors name :"); String dname = sc.next(); System.out.println("Enter the date of the appointment :"); String date = sc.next(); System.out.println("Enter your time of appointment :"); String time = sc.next(); System.out.println("Enter the type of treatment :"); String treattype = sc.next(); System.out.println("Enter the specifics of the procedure :"); String specifics = sc.next(); // 先实例化booking对象 booking newBooking = new booking(pname, dname, date, time); // 按构造方法要求的参数顺序实例化treatment对象 treatment newtreatment = new treatment(treattype, specifics, newBooking); treatmentlist.add(newtreatment); System.out.println("The dentist has been registered Successfully"); }
补充优化建议:Java编码规范要求类名采用大驼峰格式,建议将treatment改为Treatment、booking改为Booking,避免和变量名、属性名混淆。
内容的提问来源于stack exchange,提问作者chicken nuggets
相关产品推荐
相关产品推荐

