Java 将数组格式化为具有空值的句子

Java 将数组格式化为具有空值的句子,java,arrays,null,Java,Arrays,Null,所以我有这个类Food,我想使用另一个类(testFood)输出一个水果数组。我遇到的问题是以正确的句子结构输出非空值。我已经知道了如何计算数组的长度,而不考虑数组中的空值(使用新方法“realLength”),但第54行仍然存在一个问题,即元素之间存在空值,但语句没有按照我希望的方式处理它。如果有人知道如何改变这一点,我们将不胜感激 public class Food{ static final int MAX_SIZE=10; public static String[] favFr

所以我有这个类Food,我想使用另一个类(testFood)输出一个水果数组。我遇到的问题是以正确的句子结构输出非空值。我已经知道了如何计算数组的长度,而不考虑数组中的空值(使用新方法“realLength”),但第54行仍然存在一个问题,即元素之间存在空值,但语句没有按照我希望的方式处理它。如果有人知道如何改变这一点,我们将不胜感激

public class Food{
  static final int MAX_SIZE=10;
  public static String[] favFruit=new String[MAX_SIZE]; //array of favourite fruit

  //Set member function used to set a new favourite fruit in the array of favourite fruit
  public static void addFruit(String fruit){
    for(int i=0;i<MAX_SIZE;i++){
      if(favFruit[i]==null){
        favFruit[i]=fruit;
        break;
      }
    }
  }

  //Set member function used to set a favourite fruit in the array to null, thereby removing it
  public static void removeFruit(String fruit){
    for(int i=0;i<MAX_SIZE;i++){
      if(fruit==favFruit[i]){
        favFruit[i]=null;
        break;
      }
    }
  }

  //Returns the length of an array minus the amount of null values
  public static int realLength(String[] arr){
    int num=0;
    for(int i=0;i<MAX_SIZE;i++){
      if(arr[i]==null){
        num++;
      }
    }
    return MAX_SIZE-num;
  }

  //Prints the list of fruit in order to prove what is in the array of favFruit
  public static void printFruit(String[] fruits){
    //Prints no fruits and returns a statement saying why
    int length=realLength(fruits);
    if(length==0){
      System.out.println("There are no favourite fruits.");
    }
    else{
      System.out.print("The favourite fruits are: ");
      for(int i=0; i<MAX_SIZE; i++){
        //Prints the fruit without ','/'.'/'and' if and only if there is one valid fruit in the array
        if(fruits[i]!=null && length==1){
          System.out.print(fruits[i]+".");
        }
        //Prints the fruit in successive order
        else if(fruits[i]!=null && fruits[i]!=fruits[length-1]){
          System.out.print(fruits[i]+", ");
        }
        //On the last favourite fruit, this prints 'and' and '.' instead to complete the sentence
        else if(fruits[i]!=null && fruits[i]==fruits[length-1]){ //Issue: doesnt work if null is between elements
            System.out.print("and "+fruits[i]+".");
        }
      }
      System.out.println();
    }
  }
}

public class testFood{
  public static void main(String[] args){
    //Add fruit to the favFruit array to test addFruit method
    Food.addFruit("Orange");
    //Print the array to prove the array has changed
    Food.printFruit(Food.favFruit);
    //Remove fruit from the favFruit array to test the removeFruit method
    Food.removeFruit("Orange");
    //Print the array to prove the array has changed
    Food.printFruit(Food.favFruit);

    //Repeat last steps to test for multiple fruit
    Food.addFruit("Banana");
    Food.addFruit("Apple");
    Food.addFruit("Pear");
    Food.addFruit("Orange");
    Food.printFruit(Food.favFruit);
    Food.removeFruit("Apple");
    Food.printFruit(Food.favFruit);
  }
}

有几种方法可以解决这个问题。您可以创建一个实际长度的新数组,其中只包含非空的元素。虽然这不是最好的,因为每次你想造句时都会创建一个新数组。可以考虑使用字符串。列表只是一个数组,您可以在其中添加元素和删除元素,所有排序都由您负责。因此,当您删除一个元素时,不会留下null,只是列表似乎在某个位置上发生了移动

最后,如果您想继续当前的工作,我编写了一个简单但有效的实现

public class TestFood {

    public static void main(String[] args) {
        //Add fruit to the favFruit array to test addFruit method
        Food.addFruit("Orange");
        //Print the array to prove the array has changed
        System.out.println(Food.makeSentence());
        //Remove fruit from the favFruit array to test the removeFruit method
        Food.removeFruit("Orange");
        //Print the array to prove the array has changed
        System.out.println(Food.makeSentence());

        //Repeat last steps to test for multiple fruit
        Food.addFruit("Banana");
        Food.addFruit("Apple");
        Food.addFruit("Pear");
        Food.addFruit("Orange");
        System.out.println(Food.makeSentence());
        Food.removeFruit("Apple");
        System.out.println(Food.makeSentence());
    }
}

public class Food {

    static final int MAX_SIZE = 10;
    public static String[] favFruit = new String[MAX_SIZE];


    /**
     * Add's a fruit, if and only if there is a space for it.
     *
     * @param fruit Name of the fruit to be added.
     */
    public static void addFruit(String fruit) {
        for (int i = 0; i < MAX_SIZE; i++) {
            if (favFruit[i] == null) {
                favFruit[i] = fruit;
                break;
            }
        }
    }


    /**
     * Removes the specified fruit, if it does exist in the food.
     *
     * @param fruit Name of the fruit to be removed.
     */
    public static void removeFruit(String fruit) {
        for (int i = 0; i < MAX_SIZE; i++) {
            //Note the use of the 'equals' method
            if (fruit.equals(favFruit[i])) {
                favFruit[i] = null;
                break;
            }
        }
    }

    /**
     * Computes the used length of the array in this class.
     *
     * @return The length, or count of elements, used in this class.
     */
    public static int realLength() {
        int length = 0;
        for (int i = 0; i < MAX_SIZE; i++)
            if (favFruit[i] != null)
                length++;
        return length;
    }


    public static String makeSentence() {
        //Get the real length of the array
        int length = realLength();
        //Have a variable, used to tell how many more fruits are to be added.
        int fruitsToAdd = length;

        /*
        The purpose of having the two variables will be seen later. But basically
        the purpose is because of the appending of the word "and". If the real
        length of the array is 1, the fruitsToAdd variable will be 1 too. When this
        happens the word "and" will be appended even though there was only one fruit
        in the first place.
         */

        if (fruitsToAdd == 0)
            return "There are no favourite fruits.";

        //Make a StringBuilder to append everything to
        StringBuilder builder = new StringBuilder();

        //Append the start of the sentence to the StringBuilder, depending on how many elements there are
        if (length == 1)
            builder.append("The favourite fruit is: ");
        else
            builder.append("The favourite fruits are: ");

        //Go through all the elements in the array
        for (int position = 0; position < favFruit.length; position++) {

            //Test if the current position of the favourite fruits is not null
            if (favFruit[position] != null) {

                //If this is the last fruit to add, append it with "and [fruitName]."
                if (fruitsToAdd == 1)
                    //If the length was 1, no need to append "and"
                    if (length == 1)
                        builder.append(favFruit[position]).append(".");
                    else
                        //If there are more than 1 fruit, then append "and". Not you could easily make this one expression with a ternary statement
                        builder.append(" and ").append(favFruit[position]).append(".");
                    //Else, append the name of the fruit.
                else
                    builder.append(favFruit[position]);

                //If this is not the second last fruit (but is not the last element either), append a comma and a space for seperation.
                if (fruitsToAdd > 2)
                    builder.append(", ");

                //Decrement the amount of fruits to add.
                fruitsToAdd--;
            }
        }

        //Returns the String contents of the builder
        return builder.toString();
    }
}

这不是你的问题,但是:停止反复调用
realllength()
。调用它一次并存储它的结果!这也不是您的问题,但是您应该在
removeFruit(String)
方法中更改
if(fruit==favruit[i])
的测试。目前对您有效的唯一原因是您在编译之前声明了所有字符串,并且它们都是相同的。但是,假设您扩展了程序以接受用户输入。此方法将不再工作,因为每个输入都是一个新字符串且不相等。改用
String.equals(String)
方法。这将消除此潜在问题。谢谢!这很有帮助,不幸的是,我不得不使用数组而不是列表,因为有一个问题是如何具体使用数组。
public class TestFood {

    public static void main(String[] args) {
        //Add fruit to the favFruit array to test addFruit method
        Food.addFruit("Orange");
        //Print the array to prove the array has changed
        System.out.println(Food.makeSentence());
        //Remove fruit from the favFruit array to test the removeFruit method
        Food.removeFruit("Orange");
        //Print the array to prove the array has changed
        System.out.println(Food.makeSentence());

        //Repeat last steps to test for multiple fruit
        Food.addFruit("Banana");
        Food.addFruit("Apple");
        Food.addFruit("Pear");
        Food.addFruit("Orange");
        System.out.println(Food.makeSentence());
        Food.removeFruit("Apple");
        System.out.println(Food.makeSentence());
    }
}

public class Food {

    static final int MAX_SIZE = 10;
    public static String[] favFruit = new String[MAX_SIZE];


    /**
     * Add's a fruit, if and only if there is a space for it.
     *
     * @param fruit Name of the fruit to be added.
     */
    public static void addFruit(String fruit) {
        for (int i = 0; i < MAX_SIZE; i++) {
            if (favFruit[i] == null) {
                favFruit[i] = fruit;
                break;
            }
        }
    }


    /**
     * Removes the specified fruit, if it does exist in the food.
     *
     * @param fruit Name of the fruit to be removed.
     */
    public static void removeFruit(String fruit) {
        for (int i = 0; i < MAX_SIZE; i++) {
            //Note the use of the 'equals' method
            if (fruit.equals(favFruit[i])) {
                favFruit[i] = null;
                break;
            }
        }
    }

    /**
     * Computes the used length of the array in this class.
     *
     * @return The length, or count of elements, used in this class.
     */
    public static int realLength() {
        int length = 0;
        for (int i = 0; i < MAX_SIZE; i++)
            if (favFruit[i] != null)
                length++;
        return length;
    }


    public static String makeSentence() {
        //Get the real length of the array
        int length = realLength();
        //Have a variable, used to tell how many more fruits are to be added.
        int fruitsToAdd = length;

        /*
        The purpose of having the two variables will be seen later. But basically
        the purpose is because of the appending of the word "and". If the real
        length of the array is 1, the fruitsToAdd variable will be 1 too. When this
        happens the word "and" will be appended even though there was only one fruit
        in the first place.
         */

        if (fruitsToAdd == 0)
            return "There are no favourite fruits.";

        //Make a StringBuilder to append everything to
        StringBuilder builder = new StringBuilder();

        //Append the start of the sentence to the StringBuilder, depending on how many elements there are
        if (length == 1)
            builder.append("The favourite fruit is: ");
        else
            builder.append("The favourite fruits are: ");

        //Go through all the elements in the array
        for (int position = 0; position < favFruit.length; position++) {

            //Test if the current position of the favourite fruits is not null
            if (favFruit[position] != null) {

                //If this is the last fruit to add, append it with "and [fruitName]."
                if (fruitsToAdd == 1)
                    //If the length was 1, no need to append "and"
                    if (length == 1)
                        builder.append(favFruit[position]).append(".");
                    else
                        //If there are more than 1 fruit, then append "and". Not you could easily make this one expression with a ternary statement
                        builder.append(" and ").append(favFruit[position]).append(".");
                    //Else, append the name of the fruit.
                else
                    builder.append(favFruit[position]);

                //If this is not the second last fruit (but is not the last element either), append a comma and a space for seperation.
                if (fruitsToAdd > 2)
                    builder.append(", ");

                //Decrement the amount of fruits to add.
                fruitsToAdd--;
            }
        }

        //Returns the String contents of the builder
        return builder.toString();
    }
}
The favourite fruit is: Orange.
There are no favourite fruits.
The favourite fruits are: Banana, Apple, Pear and Orange.
The favourite fruits are: Banana, Pear and Orange.