我必须为涉及数组的Fruit程序编写两个方法。其中一个是public void addFruit(String other)
,另一个是public void deleteFruit(String del)
。我已经完成了deleteFruit
。
我如何进行addFruit?
我不知道代码是什么或如何编码。
public class Fruit {
private String[] bowl;
public Fruit()
{
bowl = new String[10];
bowl[0] = "apple";
bowl[1] = "banana";
bowl[2] = "kiwi";
bowl[3] = "lemon";
bowl[4] = "lime";
bowl[5] = "mango";
bowl[6] = "orange";
bowl[7] = "pear";
bowl[8] = "pineapple";
bowl[9] = "plum";
}
public Fruit(int x)
{
bowl = new String[] {"apple", "banana", "lemon", "lime", "mango"};
}
public void display()
{
for (int x = 0; x < bowl.length; x++)
System.out.println(bowl[x]);
}
public void deleteFruit(String del)
{
int index = -1;
for(int i=0; i< bowl.length; i++)
if (bowl[i].equals(del))
index = i;
if (index ==-1)
System.out.println("Not in the list");
else
{
for (int i = index; i< bowl.length -1; i++)
bowl[i] = bowl [i+1];
String[] temp = new String[bowl.length-1];
for (int i = 0; i < temp.length; i++)
temp[i]= bowl [i];
bowl = temp;
System.out.println("item deleted");
}
public void addFruit(String other)
{
}
}
答案 0 :(得分:0)
这不是最有效的解决方案,但它确实有效。
public void addFruit(String other) {
String[] res = new String[bowl.length + 1];
for(int i = 0; i < bowl.length; i++) {
res[i] = bowl[i];
}
res[res.length - 1] = other;
bowl = res;
}