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