如何在java中使用带有重载构造函数的if-else条件



我们的教授为我们提供了一个活动来创建一个存储血型的重载构造函数。我已经创建了两(2(个名为BloodData(没有类修饰符(和RunBloodRata(public(的类。我的问题是,如果用户没有输入任何内容,我不知道如何将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?

这是活动中说明的一部分--在主方法中,添加语句以要求用户输入血型和Rhesus因子(+或-(。使用基于用户输入的参数实例化BloodData对象名称。例如,BloodData bd new BloodData(inputl,input2(;其中input1和input2是存储用户输入内容的字符串变量。如果用户没有输入任何内容,则实例化不带参数的BloodData对象。通过您创建的对象调用显示方法来打印确认消息。例如,bd.disp1ay;

一个简单的方法是使用.equals((检查输入是否等于空字符串("(。例如:

if (input1.equals("") && input2.equals(""))
BloodData bd = new BloodData();
// ...
else
BloodData bd = new BloodData(input1,input2);
// ...

然而,如果您的用户没有为一个输入输入任何内容,而是为另一个输入了一些内容,则这将不起作用。我会添加一个条件来说明这一点,比如再次要求用户输入。

下面的代码将接受用户的输入,并检查两个输入是否都不是空的。若其中一个为空,那个么它将调用不带参数的构造函数,并相应地打印消息。

import org.apache.commons.lang3.StringUtils;
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();
BloodData bd = null;
if(!StringUtils.isEmpty(input1) && !StringUtils.isEmpty(input2)) {
bd = new BloodData(input1,input2);
} else {
bd = new BloodData();
}
bd.display();
System.out.println(" is added to the blood bank.");  
class BloodData {
static String bloodType;
static String rhFactor;
public BloodData() {
bloodType = "O";
rhFactor = "+";   
}
public BloodData(String bt, String rh) {
bloodType = bt;
rhFactor = rh;
}
public void display(){
System.out.print(bloodType+rhFactor);
}
}

最新更新