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

How to use if else conditions with overloaded constructor in java

我们的教授给了我们一个 activity 来创建一个存储血型的重载构造函数。我已经创建了两 (2) 个名为 BloodData(无 class 修饰符)和 RunBloodData(public)的 classes。我的问题是如果用户没有输入任何内容,我不知道如何将 if else 语句应用于 main 方法中的这 2 个对象因此,将显示存储在默认构造函数中的值。

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?

这是activity中指令的一部分。 --在main方法中,添加语句要求用户输入血型和恒河猴因子(+或-)。根据用户输入使用参数实例化 BloodData 对象名称。例如,BloodData bd new BloodData(inputl, input2);其中 input1 和 input2 是存储用户输入内容的字符串变量。如果用户没有输入任何内容,则实例化一个不带参数的 BloodData 对象。通过您创建的对象调用 display 方法来打印确认消息 例如,bd。显示;

一个简单的方法是使用 .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);
    }
}