日期:2014-05-20  浏览次数:20673 次

本人初学java ..望大哥大姐指点呀
interface Pet //宠物接口标准
{
String getName(); //获取名字抽象方法
String getColor(); //获取颜色抽象方法
int getAge(); //获取年龄抽象方法
}
class PetShop
{
private Pet a[]; //定义宠物数组
private int foot; //宠物的位置
PetShop(int len) //构造方法
{
if(len>0)
{
a=new Pet[len]; //申请动态空间
}
else
{
a=new Pet[1];
}
}
public boolean addPet(Pet b) //添加宠物
{
if(this.foot<a.length)
{
a[this.foot++]=b;
return true;
}
else
return false;
}
public Pet[] check(String keyword) //搜索关键字 {
Pet b[]=null; //先声明堆得连接
int nCount=0; //记录关键字的个数
for(int x=0;x<this.a.length;x++)
{
if(this.a[x].getName()!=null) //首先确认该节点是否存在具体的宠物
{
if(this.a[x].getName().indexOf(keyword)!=-1||this.a[x].getColor().indexOf(keyword)!=-1);
{
nCount++; //记录查询的结果
}
}
}
b=new Pet[nCount]; //申请空间
nCount=0;
for(int x=0;x<this.a.length;x++)
{
if(this.a[x].getName()!=null) //首先确认该节点是否存在具体的宠物
{
if(this.a[x].getName().indexOf(keyword)!=-1||this.a[x].getColor().indexOf(keyword)!=-1);
{
b[nCount++]=this.a[x];//记录查询的结果
}
}
}
  return b;
}
}
class Cat implements Pet
{
private String name; //定义姓名字段
private String color; //设置颜色字段
private int age; //设置年龄字段
Cat(String name,String color,int age) //构造函数
{
this.setName(name);
this.setColor(color);
this.setAge(age);
}
public void setName(String name) //设置姓名字段
{
this.name=name;
}
public void setColor(String color) //设置颜色字段
{
this.color=color;
}
  public void setAge(int age) //设置年龄字段
{
this.age=age;
}
  public String getName() //获取姓名字段
{
  return this.name;
}
public String getColor() //获取颜色字段
{
return this.color;
}
public int getAge() //获取年龄字段
{
return this.age;
}
}
class Dog implements Pet
{
private String name; //定义姓名字段
private String color; //设置颜色字段
private int age; //设置年龄字段
Dog(String name,String color,int age) //构造函数
{
this.setName(name);
this.setColor(color);
this.setAge(age);
}
public void setName(String name) //设置姓名字段
{
this.name=name;
}
public void setColor(String color) //设置颜色字段
{
this.color=color;
}
  public void setAge(int age) //设置年龄字段
{
this.age=age;
}
  public String getName() //获取姓名字段
{
  return this.name;
}
public String getColor() //获取颜色字段
{
return this.color;
}
public int getAge() //获取年龄字段
{
return this.age;
}
}
public class Num2
{
  public static void main(String args[])
{
PetShop a=new PetShop(3); //声明宠物商店对象
a.addPet(new Cat("白猫","黄色",2));
a.addPet(new Cat("黑猫","白色",1));
a.addPet(new Dog("黑狗","黑色",3));
 
for(int x=0;x<a.check("白色").length;x++)
{
System.out.println("关键字查询下白色的宠物有:\n"+"姓名为:"+a.check("白色")[x].getName()+"\n颜色为:"+a.check("白色")[x].getColor()+"\n年龄为:"+a.check("白色")[x].getAge());
}
  }
}
写起代码,然后运行时。。不论我在a.check("")里边写什么颜色,都是将我全部的信息输出了。。求大侠解释一下。。谢谢呀。。

------解决方案--------------------
if (this.a[x].getName().indexOf(keyword) != -1
|| this.a[x].getColor().indexOf(keyword) != -1)
;
多了一个;
------解决方案--------------------