关闭

Java数组需要new两次

标签: java数组
202人阅读 评论(0) 收藏 举报
分类:

上代码:

import java.io.*;
public class Array 
{

	public static void main(String[] args) throws Exception
	{
		// TODO Auto-generated method stub
		//定义可以存放四只狗的数组
		Pig pigs[]=new Pig[4];
		//从控制台输入
		InputStreamReader isr=new InputStreamReader(System.in);
		BufferedReader br= new BufferedReader(isr);
		
<span style="white-space:pre">		</span>for(int i=0;i<4;i++)
		{
			pigs[i]=new Pig();
			System.out.println("Input the dog's name:");
			String name= br.readLine();
			pigs[i].setName(name);
			System.out.println("Input the dog's weight:");
			String s_weight=br.readLine();
			float weight= Float.parseFloat(s_weight); //String->weight
			//将名字赋给对象
			pigs[i].setWeight(weight);
		}
		
		//计算平均体重
		float all_weight=0;
		for(int i=0;i<4;i++)
		{
			all_weight+=pigs[i].getWeight();
		}
		
		float ave_weight = all_weight / pigs.length;
		System.out.println("all_weight : "+all_weight+" Ave_weight = "+ave_weight);
		
		//比较字符串是否相等时应该用equal 而不应该用“==”;
	}

}

class Pig
{
	private String name;
	private float weight;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public float getWeight() {
		return weight;
	}
	public void setWeight(float weight) {
		this.weight = weight;
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11142次
    • 积分:289
    • 等级:
    • 排名:千里之外
    • 原创:15篇
    • 转载:22篇
    • 译文:0篇
    • 评论:1条
    最新评论