1. 编程练习
功能描述:为指定成绩加分,直到分数大于等于 60 为止,输出加分前和加分后的成绩,并统计加分的次数
public class HelloWorld { public static void main(String[] args) { // 变量保存成绩 int score = 53; // 变量保存加分次数 int count = 0; //打印输出加分前成绩 System.out.println("加分前成绩:" + score); // 只要成绩小于60,就循环执行加分操作,并统计加分次数 for(; score < 60; score++, count++); //打印输出加分后成绩,以及加分次数 System.out.println("加分后成绩:" + score); System.out.println("共加了" + count + "次!"); } }
2. 编程练习解析
package com.imooc; public class Demo02 { public static void main(String[] args) { int score = 53; int count = 0; System.out.println("score before changing:" + score); while(score < 60) { score++; count++; } System.out.println("score after changing:" + score); System.out.println("count:" + count); } }
3. 编程练习优化(增加用户输入信息)
package com.imooc; import java.util.Scanner; /*使用Scanner工具类来获取用户输入的成绩信息 * Scanner类诶与java.util包中,使用时需要导入此包 * 步骤: * 1.导入java.util.Scanner * 2.创建Scanner对象 * 3.接收并保存用户输入的值 */ public class Demo02 { public static void main(String[] args) { Scanner input = new Scanner(System.in); //创建Scanner对象 System.out.print("please input score: "); //print显示同行,println会换行 int score = input.nextInt(); //获取用户输入的成绩并保存在变量中 int count = 0; System.out.println("score before changing:" + score); while(score < 60) { score++; count++; } System.out.println("score after changing:" + score); System.out.println("count:" + count); } }
4. 使用Eclipse调试程序
5. 进阶练习
package com.imooc; import java.util.Scanner; /*功能:实现接收三个班级的各四名学院的成绩信息,然后计算每个班级学员的平均分 * 知识点:二重循环(外层控制班级,内层控制学员) */ public class Demo03 { public static void main(String[] args) { int classNum = 3; //班级数量 int stuNum = 4; //学生数量 double sum = 0; //成绩总和 double avg = 0; //成绩平均分 Scanner input = new Scanner(System.in); //创建Scanner对象 for (int i=1; i <= classNum; i++) { System.out.println("***please input the score of the "+i+"th class***:"); for (int j=1; j <= stuNum; j++) { System.out.println("please input the score of the "+j+"th student:"); int score = input.nextInt(); sum = sum + score; } avg = sum / stuNum; sum = 0; //should zero variable "sum" System.out.println("the average score of the"+i+"th class is:"+avg); } } }