2014-10-09 3 views
-1

그래서이 클래스 Food가 있고 다른 클래스 (testFood)를 사용하여 과일 배열을 출력하고 싶습니다. 내가 겪고있는 문제는 적절한 문장 구조로 null이 아닌 값을 출력하는 것입니다. 배열의 null 값을 할인하는 방법을 알아 냈습니다 (새로운 메서드 "realLength"사용). 그러나 요소 사이에 null 값이 있지만 명령문은 여전히 ​​54 행에 문제가 있습니다. 내가 원한 방식대로 처리하지 못한다. 누군가가 이것을 바꿀 수있는 방법을 알고 있다면, 크게 감사하겠습니다!null 값을 갖는 문장으로 배열 서식 지정

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])'테스트입니다. 현재이 기능이 작동하는 유일한 이유는 컴파일하기 전에 모든 문자열을 선언했기 때문입니다. 모두 동일합니다. 그러나 사용자 입력을 위해 프로그램을 확장했다고 가정 해 보겠습니다. 이 메소드는 각 입력이 * new * String이며 동일하지 않기 때문에 더 이상 작동하지 않습니다. 대신에'String.equals (String)'메쏘드를 사용하십시오. 이 잠재적 인 문제점을 제거합니다. –

답변

1

당신이이 문제를 방지 할 수있는 몇 가지 방법이 있습니다. 실제 길이가 인 새 배열을 null이 아닌 요소만으로 만들 수 있습니다. 비록 당신이 문장을 만들고 싶을 때마다 새로운 배열을 생성 할 것이기 때문에 이것은 최선이 아닙니다. 문자열의 List 사용을 고려해 볼 수 있습니다. 목록은 요소를 추가하고 요소를 제거 할 수있는 배열이며 모든 순서는 사용자를 위해 처리됩니다. 따라서 요소를 제거하면 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(); 
    } 
} 

날의 출력했다 :

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

관련 문제