【发布时间】:2020-10-30 06:19:24
【问题描述】:
我们的教授给了我们一个活动来创建一个存储血型的重载构造函数。我已经创建了两 (2) 个名为 BloodData(无类修饰符)和 RunBloodData(公共)的类。我的问题是,如果用户没有输入任何内容,我不会在 main 方法中将 if else 语句应用于这两个对象。因此,将显示存储在默认构造函数中的值。
public class RunBloodData {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter blood type of patient: ");
String input1 = input.nextLine();
System.out.print("Enter the Rhesus Factor (+ or -): ");
String input2 = input.nextLine();
//How to use conditions in this 2 objects with agruments and w/out arguments?
BloodData bd = new BloodData(input1,input2);
bd.display();
System.out.println(" is added to the blood bank.");
// if the user did not input values, the values stored in the default constructor should display this.
BloodData bd = new BloodData();
bd.display();
System.out.println(" is added to the blood bank.");
//constructor
class BloodData {
static String bloodType;
static String rhFactor;
public BloodData() {
bloodType = "O";
rhFactor = "+";
}
public BloodData(String bt, String rh) {
bloodType = bt;
rhFactor = rh;
}static
public void display(){
System.out.print(bloodType+rhFactor);
}
}
// this is the output of it
Enter blood type of patient: B
Enter the Rhesus Factor (+ or -): -
B- is added to the blood bank.
O+ is added to the blood bank.//this should not be displayed since the user input values. How to fix it?
这是活动说明的一部分。 --在main方法中,添加语句让用户输入血型和Rhesus因子(+或-)。根据用户输入使用参数实例化 BloodData 对象名称。例如,BloodData bd new BloodData(inputl, input2);其中 input1 和 input2 是存储用户输入内容的字符串变量。如果用户没有输入任何内容,则实例化一个不带参数的 BloodData 对象。通过您创建的对象调用 display 方法打印确认消息 例如,bd。显示;
【问题讨论】:
标签: java if-statement constructor-overloading