1.程序要求实现根据用户提供的名称在寄养的宠物中查找宠物并输出该宠物的类型及创建序号。
2程序提供对宠物的信息输出功能(信息输出,如:喂养序号为1,名称为大黄的宠物狗,可以输出“1 狗 大黄”),可根据类型输出所有类型相同的宠物;并可根据寄样序号,输出该序号之前所有当前在店中寄样的宠物。
我在设计时似乎用数组不能实现对宠物信息的储存和再读取,部分代码如下:
class Pet{
int rank;
int []number = new int[10];
String []name = new String[10];
char []species = new char[10];
PetShop st = new PetShop();
char D = 'd';
char C = 'c';
char R = 'r';
public void CreatePet() {
int m = 0;
System.out.println("请输入您宠物的昵称:");
for(int i = 0;i<10;i++) {
if(number[i] == m) {
name[i] = input01.nextLine();
number[i] = i;
if(chosenFounction02 == 1) {
species[i] = D;
}
else if (chosenFounction02 == 2) {
species[i] = C;
}
else if (chosenFounction02 ==3) {
species[i] = R;
}
System.out.println("您宠物的序号是:"+number[i]);
break;
}
else if(number[i] != 0) {
continue;
}
}//这是负责创建对象的代码
public void SearchPet(String str){
int times = 0;
for(int i = 0;i<10;i++){
if(name[i] == null) {
continue;
}
else if(name[i].equals(str)){
times++;
if(species[i] == 'd'){
System.out.println(i+" 狗 ");
}
else if(species[i] == 'c'){ //这里报错java.lang.NullPointerException
System.out.println(i+" 猫 ");
}
else if(species[i] == 'r'){
System.out.println(i+" 兔子 ");
}
break;
}
else{
if(times == 0){
System.out.println("很抱歉您的宠物不在我们商店里哦~");
dialog();
st.InputFounction();
}
else {
continue;
}
}//这是负责查询对象的代码
数组存储数据在内存,并不是持久化的数据(持久化就是永久保存:保存到数据库或者一个文件里面)。你要先把数据持久化,查询的时候从持久化中获取
应该建立对象数组去保存,你这个Pet类都不能算Pet类。用面向对象的思想去设计,Pet类应该有你要的序号、种类、宠物名,
然后数组的话建立一个Pet数组去存储就行了,这样才符合我们人的思路
Pet类的设计应该是
/**
* @version 1.0
* @date 2019/4/25 14:18
**/
public class Pet {
/**
* 序号
*/
int number;
/**
* 种类
*/
String specie;
/**
* 名称
*/
String name;
/**
* 创建宠物,使用构造函数
*/
public Pet(int number, String specie, String name) {
this.number = number;
this.specie = specie;
this.name = name;
}
public static void main(String[] args) {
Pet[] pet = new Pet[10];
pet[0] = new Pet(1, "狗", "大黄");
searchPet(pet, 1);
}
static void searchPet(Pet[] pet, int number) {
for (int i = 0; i < pet.length; i++) {
if (pet[i] != null) {
if (pet[i].number == number) {
System.out.println(pet[i]);
return;
}
}
}
System.out.println("找不到你要的宠物");
}
@Override
public String toString() {
return number + " "+ specie + " " + name;
}
}