实验3 /* * @(#)AverageNumbers2 * * Copyright 2008 School of Software, Yunnan University. * All rights reserved */ package cn.edu.ynu.sei.Java_Labs.Lab3; /** * 求1-50的平均数 * @version 1.0.0.0 Jan 22, 2008 * @author eleven */ public class AverageNumbers2 { private double result1; private double sum1; private double result2; private double sum2; /** * 使用for循环计算 */ public double DeterminAverageUsingFor(int startNumber, int endNumber) { for (int i = startNumber; i <= endNumber; i++) { sum1 += i; result1 = sum1 / 50; } return result1; } /** * 使用while循环计算 */ public double DeterminAverageUsingWhile(int startNumber, int endNumber) { int i = startNumber; while (i <= endNumber) { sum2 += i; result2 = sum2 / 50; i++; } return result2; } public static void main(String[] args) { AverageNumbers2 an2 = new AverageNumbers2(); double finalResult1 = an2.DeterminAverageUsingFor(1, 50); double finalResult2 = an2.DeterminAverageUsingWhile(1, 50); System.out.println("average of numbers is " + finalResult1 + ", which is calculated by for loop."); System.out.println("average of numbers is " + finalResult2 + ", which is calculated by while loop."); } } /* * @(#)BreakLoop * * Copyright 2008 School of Software, Yunnan University. * All rights reserved */ package cn.edu.ynu.sei.Java_Labs.Lab3; /** * 显示数字1-10,但是在5处跳出,并且打印 * @version 1.0.0.0 Jan 23, 2008 * @author eleven */ public class BreakLoop { public BreakLoop() { for (int i = 1; i <= 10; i++) { if (i < 5) { System.out.println("Count = " + i); } if (i == 5) { System.out.println("Broke out of the loop at count = " + i); break; } } } public static void main(String[] args) { BreakLoop bl = new BreakLoop(); } } /* * @(#)ContinueLoop * * Copyright 2008 School of Software, Yunnan University. * All rights reserved */ package cn.edu.ynu.sei.Java_Labs.Lab3; /** * * @version 1.0.0.0 Jan 23, 2008 * @author eleven */ public class ContinueLoop { private int j; public ContinueLoop() { for (int i = 1; i <= 10; i++) { if (i < 5) { System.out.println("Count = " + i); } if (i == 5) { j = i; continue; } else { System.out.println("Count = " + i); } } System.out.println("Used continue statement to skip printing" + j); } public static void main(String[] args) { ContinueLoop cl = new ContinueLoop(); } }