1
回答
Java基础程序设计数组问题
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   
想要做一个关于人口普查的java代码,在计算数组的时候出现了点问题,求指教啊。。。

想要在程序的最后加一段计算household中有小孩的比例以及5岁以下孩子的比例。。。


import java.util.*;

public class Census {
	private Scanner reader = new Scanner(System.in);
	
	public void runSurvey() {
		int choice, i, j, averageAge = 0;
		int sum=0;
	
		do
		{
				System.out.println("Welcome to KID E-CENSUS");
				System.out.print("How many households are you surveying?");
				
				choice = reader.nextInt();
				
				while(choice < 0)
				{	
					System.out.print("Sorry, the number must be 0 or greater. Try again: ");
					choice = reader.nextInt();
				}
				
				int[] household = new int[choice];
				
				ArrayList age = new ArrayList();
				
				for(i=0; i<=(choice-1); i++){
					
					System.out.print("For household "+i+" how many people are under the age of 18?");
					household[i]=reader.nextInt();
					
				if(choice==1 && household[i]==0){
					
					System.out.println("No children were resident in any house");
				break;
				
				}
				
				}
				

				for(j=0; j<=(household[i]-1); j++){
					
					System.out.print("What is the age of child number "+j+" ?");

				int temp = reader.nextInt();
				
				while(temp < 0){
					
					System.out.print("Sorry, the number must be 0 or greater. Try again: ");
					temp = reader.nextInt();

					}

					sum += temp;
					age.add(temp);

					averageAge = sum/age.size();
					System.out.println("The average child age was "+ averageAge);
					}
				
				break;
				
			} while (choice == 0);
					
					System.out.println("Thank you for being a surveyor");
	}
}

输出结果为:



举报
ysun20
发帖于4年前 1回/126阅
顶部