新建一个羊类,然后在建一个羊类数组,然后对每个羊进行赋值,分类。最后显示输出。
import java.util.Scanner;
class Sheep{
private String type;
private int id;
private double wight;
private String color;
public Sheep(){}
public Sheep(String type,int id,double wight,String color){
this.type=type;
this.id=id;
this.wight=wight;
this.color=color;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setWight(double wight) {
this.wight = wight;
}
public double getWight() {
return wight;
}
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void show(){
System.out.println("羊的属性:类型-"+this.type+"编号-"+this.id+"颜色-"+this.color+"重量-"+this.wight);
}
}
class SheepArray{
private Sheep []a=new Sheep[10];
private int maxsheep;
private String name;
public SheepArray(){
for(int i=0;i<10;i++)
a[i]=new Sheep();
;不初始化会产生空指针数组。。。。。
}
public SheepArray(int maxsheep,String name){
this.maxsheep=maxsheep;
this.name=name;
for(int i=0;i<10;i++)
a[i]=new Sheep();;不初始化会产生空指针数组。。。。。
}
public void setMaxsheep(int maxsheep) {
this.maxsheep = maxsheep;
}
public int getMaxsheep() {
return maxsheep;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setA(int i) {
String type;int id;double wight;String color;
Scanner scan=new Scanner(System.in);
System.out.println("请输入羊的编号:");
id=scan.nextInt();
a[i].setId(id);
System.out.println("请输入羊的类型:");
type=scan.next();
a[i].setType(type);
System.out.println("请输入羊的重量:");
wight=scan.nextInt();
a[i].setWight(wight);
System.out.println("请输入羊的颜色:");
color=scan.next();
a[i].setColor(color);
}
public int maxwight(int n){
int z=0;
for(int i=0;i<n;i++){
if(a[i].getWight()>a[i+1].getWight())
z=i;
}
return z;
}
public void show(int n){
for(int i=0;i<n;i++)
System.out.println(a[i].getId()+"号羊的颜色:"+a[i].getColor()+";"+"羊的类型:"+a[i].getType()+";"+"羊的重量:"+a[i].getWight());
}
}
public class TestSheep {
public static void main(String []args){
int n;
SheepArray aa=new SheepArray(10,"bitte");
Scanner scan=new Scanner(System.in);
System.out.println("请输入要养多少只羊:");
n=scan.nextInt();
System.out.println("请输入每只羊的信息:");
for(int j=0;j<n;j++)
aa.setA(j);
aa.show(n);
}
}