JAVA第七次作业
上机练习
1.编写一个简单程序,要求数组长度为5,静态赋值10,20,30,40,50,在控制台输出该数组的值。
package mt.box; public class mt1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int a[]={10,20,30,40,50}; for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } }
2.编写一个简单程序,要求数组长度为5,动态赋值,并在控制台输出该数组的值。
package mt.box; import java.util.Scanner; public class mt2 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int a[]=new int[5]; Scanner input=new Scanner(System.in); System.out.println("输入五个数"); for (int i = 0; i < a.length; i++) { a[i]=input.nextInt(); } System.out.println(" "); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } }
3.定义字符型数组,分别存储c、h、 i、n、a 并在控制台输出
package mt.box; public class mt3 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub char a[]={'c','h','i','n','a'}; for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } }
4.输入5个学生成绩,求总分和平均分
package mt.box; import java.util.Scanner; public class mt4 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int a[]=new int[5]; int sum=0; Scanner input=new Scanner(System.in); System.out.println("输入五个学生的成绩"); for (int i = 0; i < a.length; i++) { a[i]=input.nextInt(); sum+=a[i]; } System.out.println("总分为"+sum); System.out.println("平均分为"+sum/5); } }
5.定义数组{12,53,23,44,53} 用for和foreach分别输出,再倒序输出
package mt.box; public class mt5 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int a[]={12,53,23,44,53}; for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } System.out.println(" "); for (int i : a) { System.out.println(i); } System.out.println("倒序输出"); for (int i = a.length-1; i >=0; i--) { System.out.println(a[i]); } } }
作业:
1.定义一个整型数组,赋值后求出奇数个数和偶数个数
package mtbox; public class zuoye7 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] array = {0, 1, 2, 3, 4, 5}; int odd = 0; int even = 0; for (int n : array) { if (n % 2 != 0) { odd++; } else { even++; } } System.out.println(odd); System.out.println(even); } }
2.生成一个100长度数组,里面的数分别是1-100,并输出
package mtbox; public class zuoye7 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] array = new int[100]; for (int n = 0; n < 100; n++) { array[n] = n + 1; } for (int n : array) { System.out.println(n); } } }
3.定义一个double数组,存放10个学生的成绩,给所有同学加5分,不能超过100分。
package mtbox; public class zuoye7 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub double[] grades = {70, 60, 25, 65, 100, 25, 70, 20, 100}; for (int n = 0; n < grades.length; n++) { double grade = grades[n] + 5; if (grade > 100) { grade = 100; } grades[n] = grade; } for (double grade : grades) { System.out.println(grade); } } }