2014-10-09 3 views
-1

Итак, у меня есть этот класс 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); 
    } 
} 

Пример вывода:

The favourite fruits are: Orange. 
There are no favourite fruits. 
The favourite fruits are: Banana, Apple, Pear, and Orange. 
The favourite fruits are: Banana, and Pear.Orange, 
+1

не ваш вопрос, но: прекратите называть 'realLength()' снова и снова. Позвоните один раз и сохраните результат! – John3136

+0

Это тоже не ваша проблема, но что-то, что вы должны изменить в методе 'removeFruit (String)', - это тестирование 'if (fruit == favFruit [i])'. Единственная причина, по которой это работает на данный момент, состоит в том, что вы объявили все строки перед компиляцией, и все они одинаковы. Однако, скажем, вы расширили программу для ввода пользовательского ввода. Этот метод больше не будет работать, поскольку каждый вход является * новой * Строкой и не равен. Вместо этого используйте метод 'String.equals (String)'. Это устранит эту потенциальную проблему. –

ответ

1

Есть несколько способов, вы можете борьбы с этой проблемой. Вы можете создать новый массив реальной длины, содержащий только те элементы, которые не равны нулю. Хотя это не самое лучшее, так как вы будете создавать новый массив каждый раз, когда хотите сделать предложение. Вы можете рассмотреть возможность использования строки List. Список - это просто массив, в который вы можете добавлять элементы и удалять элементы, и все заказы заботятся о вас. Поэтому, когда вы удаляете элемент, вы не остаетесь с нулевым значением, но просто список, по-видимому, перемещается по месту.

Наконец, если вы хотите продолжить, как вы сейчас находитесь, я написал простую, но эффективную реализацию.

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. 
+0

Спасибо! Это очень помогает, к сожалению, меня заставили использовать массивы, а не списки из-за вопроса о том, чтобы использовать массив. – Sythe

Смежные вопросы