数姐越界
package lxh;
interface Pet{
public String getName();
public int getAge();
public String getColor();
}
class Cat implements Pet{
private String name;
private int age;
private String color;
public Cat(String name,int age,String color){
this.setName(name);
this.setAge(age);
this.setColor(color);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
class Dog implements Pet{
private String name;
private int age;
private String color;
public Dog(String name,int age,String color){
this.setName(name);
this.setAge(age);
this.setColor(color);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
class Petshop{
private int floot;
private Pet[] pers;
public int getFloot() {
return floot;
}
public void setFloot(int floot) {
this.floot = floot;
}
public Pet[] getPers() {
return pers;
}
public void setPers(Pet[] pers) {
this.pers = pers;
}
public Petshop(int len){
if(len>0){
this.pers = new Pet[len];
}else{
this.pers = new Pet[1];
}
}
public boolean add(Pet p){
if(this.floot<pers.length){
pers[floot] = p;
this.floot++;
return true;
}else{
return false;
}
}
public Pet[] search(String keywork){
Pet[] p = null;
int count = 0;
for(int i=0;i<pers.length;i++){
if(pers[i]!=null){
if(pers[i].getName().indexOf(keywork)!=-1||pers[i].getColor().indexOf(keywork)!=-1){
count++;
}
}
}
p = new Pet[count];
int f = 0;
for(int i=0;i<pers.length;i++){
if(pers[i]!=null){
if(pers[i].getName().indexOf(keywork)!=0||pers[i].getColor().indexOf(keywork)!=-1){
p[f] = this.pers[i];
f++;
}
}
}
return p;
}
}
public class PetshopDemo {
public static void main(String[] args) {
Petshop pet = new Petshop(6);
pet.add(new Dog("旺财",11,"白"));
pet.add(new Dog("阿财",11,"金"));
pet.add(new Cat("小白",11,"白"));
pet.add(new Cat("小黑",11,"黑"));
pet.add(new Cat("黑白",11,"黑白"));
print(pet.search("旺"));
for(int i=0;i<pet.getPers().length;i++){
System.out.println(pet.getPers()[i].getName()+pet.getPers()[i].getAge()+pet.getPers()[i].getColor());
}
}
public static void print(Pet p[]){
for(int i=0;i<p.length;i++){
if(p[i]!=null){
System.out.println(p[i].getName()+p[i].getAge()+p[i].getColor());
}
}
}
}
编译提示:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 1
at lxh.Petshop.search(PetshopDemo.java:112)
at lxh.PetshopDemo.main(PetshopDemo.java:129)
请高手看下错哪里了?
------解决方案--------------------
if(pers[i].getName().indexOf(keywork)!=0||pers[i].getColor().indexOf(keywork)!=-1){
太不细心了