Java实验三:程序结构和数组

  • 实验名称

程序结构和数组

  • 实验目的及要求(本次上机实验所涉及并要求掌握的知识点)

1. 熟练掌握选择、分支、循环程序设计;

2. 熟练掌握数组的定义和使用。

  • 实验环境(本次上机实践所使用的平台和相关软件)

多媒体微型计算机;Windows ,jdk及Eclipse。

  • 实验设计
  1. 实验内容

(1)输入年份和月份,输出该月的天数。(要求采用开关语句实现多路分支)。

(2)利用随机函数产生整数给含100个元素数组赋值,输出该数组,按每行5个元素的形式安排输出,统计能被3或7整除的元素的个数并输出统计结果。

(3)利用扫描器从键盘输入20个整数,计算这些数的平均值,统计大于平均值的元素个数。

  1. 实验步骤
  1. 程序1
 package shiyan3;

import java.util.Scanner;



public class shiyan3_1 {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.print("请输入年份:");

int year = scan.nextInt();

System.out.print("请输入月份:");

int month = scan.nextInt();



switch(month) {

      case 1:

      case 3:

      case 5:

      case 7:

      case 8:

      case 10:

      case 12:

      System.out.print(year+"年"+month+"月有31天");

      break;

     

      case 4:

      case 6:

      case 9:

      case 11:

      System.out.print(year+"年"+month+"月有30天");

      break;

     

      case 2:

      if((year % 4 == 0&& year % 100 !=0 ) || year % 400 == 0)

      System.out.print(year+"年"+month+"月有29天");

      else 

      System.out.print(year+"年"+month+"月有28天");

      break;

     

      default:

      System.out.println("您的输入有误!");

      break;

}
  1. 程序2
  package shiyan3;



public class shiyan3_2 {

public static void main(String a[ ]) {

System.out.printf("随机函数产生整数给含100个元素数组赋值:\n");

int m=0,n=0;

int score[]=new int[100];

for(int k=0; k<100; k++)

{

score[k]=(int)(1+Math.random()*101);//随机生成点数

if(score[k]%3==0 || score[k]%7==0)

{

n++;

}

System.out.printf("%d ",score[k]);

m++;

if(m%5==0)

    {

  System.out.printf("\n");

}

 }

System.out.printf("被3或7整除的元素的个数:%d\n",n);

}  

}
  1. 程序3
 package shiyan3;



import java.util.Scanner;



public class shiyan3_3 {

  public static void main(String a[ ]) {

  int m=0;

  double aver=0.0;

  System.out.printf("请输入20个整数:\n");

  Scanner scan=new Scanner(System.in);   

  int score[]=new int[20];

  for(int k=0; k<20; k++)

  {

  score[k]=scan.nextInt();

  aver+=score[k];

  }

  aver=aver/20;

  for(int k=0; k<20; k++)

  {

  if(score[k] > aver)

  {

  m++;

  }

  }

  System.out.printf("平均值:%f\n大于平均值的元素个数:%d",aver,m);

  }  

}

猜你喜欢

转载自blog.csdn.net/MYSELFWJC/article/details/131802973