标签:
1 public class Prime { 2 /******************************************************* 3 * Finds and prints n prime integers 4 * Jeff Offutt, Spring 2003 5 ******************************************************/ 6 public void printPrimes (int n) 7 { 8 int curPrime; // Value currently considered for primeness 9 int numPrimes; // Number of primes found so far. 10 boolean isPrime; // Is curPrime prime? 11 int [] primes = new int [100]; // The list of prime numbers. 12 13 // Initialize 2 into the list of primes. 14 primes [0] = 2; 15 numPrimes = 1; 16 curPrime = 2; 17 while (numPrimes < n) 18 { 19 curPrime++; // next number to consider ... 20 isPrime = true; 21 for (int i = 0; i <= numPrimes-1; i++) 22 { // for each previous prime. 23 if (curPrime%primes[i] == 0) 24 { // Found a divisor, curPrime is not prime. 25 isPrime = false; 26 break; // out of loop through primes. 27 } 28 } 29 if (isPrime) 30 { // save it! 31 primes[numPrimes] = curPrime; 32 numPrimes++; 33 } 34 } // End while 35 36 // Print all the primes out. 37 for (int i = 0; i <= numPrimes-1; i++) 38 { 39 System.out.println ("Prime: " + primes[i]); 40 } 41 } // end printPrimes 42 }
1 import static org.junit.Assert.*; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.PrintStream; 5 6 import org.junit.*; 7 8 public class PrimeTest { 9 Prime p; 10 PrintStream console = null; // 声明(为null):输出流 (字符设备) console 11 ByteArrayOutputStream bytes = null; // 声明(为null):bytes 用于缓存console 重定向过来的字符流 12 @Before 13 public void setup() 14 { 15 p = new Prime(); 16 bytes = new ByteArrayOutputStream(); // 分配空间 17 console = System.out; // 获取System.out 输出流的句柄 18 System.setOut(new PrintStream(bytes)); // 将原本输出到控制台Console的字符流 重定向 到 bytes 19 } 20 @After 21 public void tearDown() 22 { 23 System.setOut(console); 24 } 25 @Test 26 public void test() { 27 p.printPrimes(3); 28 String s = new String("Prime: 2\r\nPrime: 3\r\nPrime: 5\r\n"); // 注意:控制台的换行,这里用 ‘\n‘ 表示 29 assertEquals("11111111",s, bytes.toString()); // bytes.toString() 作用是将 bytes内容 转换为字符流 30 31 } 32 33 }
标签:
原文地址:http://www.cnblogs.com/c337134154/p/5339576.html