1.打印HelloWorld /****************************************************************************** * Compilation: javac HelloWorld.java * Execution: java HelloWorld * * Prints "Hello, World". By tradition, this is everyone's first program. * * % java HelloWorld * Hello, World * * These 17 lines of text are comments. They are not part of the program; * they serve to remind us about its properties. The first two lines tell * us what to type to compile and test the program. The next line describes * the purpose of the program. The next few lines give a sample execution * of the program and the resulting output. We will always include such * lines in our programs and encourage you to do the same. * ******************************************************************************/ public class HelloWorld { public static void main(String[] args) { // Prints "Hello, World" to the terminal window. System.out.println("Hello, World"); } }
2.系统函数print和println
/****************************************************************************** * Compilation: javac UseArgument.java * Execution: java UseArgument yourname * * Prints "Hi, Bob. How are you?" where "Bob" is replaced by the * command-line argument. * * % java UseArgument Bob * Hi, Bob. How are you? * * % java UseArgument Alice * Hi, Alice. How are you? * ******************************************************************************/ public class UseArgument { public static void main(String[] args) { System.out.print("Hi, "); System.out.print(args[0]); System.out.println(". How are you?"); } }
3.申明一个字符串变量 /****************************************************************************** * Compilation: javac Ruler.java * Execution: java Ruler * * Prints the relative lengths of the subdivisions on a ruler. * * % java Ruler * 1 * 1 2 1 * 1 2 1 3 1 2 1 * 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 * 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 * ******************************************************************************/ public class Ruler { public static void main(String[] args) { String ruler1 = " 1 "; String ruler2 = ruler1 + "2" + ruler1; String ruler3 = ruler2 + "3" + ruler2; String ruler4 = ruler3 + "4" + ruler3; String ruler5 = ruler4 + "5" + ruler4; System.out.println(ruler1); System.out.println(ruler2); System.out.println(ruler3); System.out.println(ruler4); System.out.println(ruler5); } }
4.申明int型变量 /****************************************************************************** * Compilation: javac IntOps.java * Execution: java IntOps a b * * Illustrates the integer operations a + b, a * b, a / b, and a % b. * * % java IntOps 1234 99 * 1234 + 99 = 1333 * 1234 * 99 = 122166 * 1234 / 99 = 12 * 1234 % 99 = 46 * 1234 = 12 * 99 + 46 * * % java IntOps 10 -3 * 10 + -3 = 7 * 10 * -3 = -30 * 10 / -3 = -3 * 10 % -3 = 1 * 10 = -3 * -3 + 1 * ******************************************************************************/ public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); System.out.println(a + " = " + quot + " * " + b + " + " + rem); } }
5.申明double型变量
/****************************************************************************** * Compilation: javac Quadratic.java * Execution: java Quadatic b c * * Given b and c, solves for the roots of x*x + b*x + c. * Assumes both roots are real valued. * * % java Quadratic -3.0 2.0 * 2.0 * 1.0 * * % java Quadratic -1.0 -1.0 * 1.618033988749895 * -0.6180339887498949 * * Remark: 1.6180339... is the golden ratio. * * % java Quadratic 1.0 1.0 * NaN * NaN * * ******************************************************************************/ public class Quadratic { public static void main(String[] args) { double b = Double.parseDouble(args[0]); double c = Double.parseDouble(args[1]); double discriminant = b*b - 4.0*c; double sqroot = Math.sqrt(discriminant); double root1 = (-b + sqroot) / 2.0; double root2 = (-b - sqroot) / 2.0; System.out.println(root1); System.out.println(root2); } }
6.关于boolean值的使用
/****************************************************************************** * Compilation: javac LeapYear.java * Execution: java LeapYear n * * Prints true if n corresponds to a leap year, and false otherwise. * Assumes n >= 1582, corresponding to a year in the Gregorian calendar. * * % java LeapYear 2004 * true * * % java LeapYear 1900 * false * * % java LeapYear 2000 * true * ******************************************************************************/ public class LeapYear { public static void main(String[] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear; // divisible by 4 isLeapYear = (year % 4 == 0); // divisible by 4 and not 100 isLeapYear = isLeapYear && (year % 100 != 0); // divisible by 4 and not 100 unless divisible by 400 isLeapYear = isLeapYear || (year % 400 == 0); System.out.println(isLeapYear); } } 7.系统函数random函数获取随机整形值/****************************************************************************** * Compilation: javac RandomInt.java * Execution: java RandomInt N * * Prints a pseudo-random integer between 0 and N-1. * Illustrate an explicit type conversion (cast) from double to int. * * % java RandomInt 6 * Your random integer is: 5 * * % java RandomInt 6 * Your random integer is: 0 * * % java RandomInt 1000 * Your random integer is: 129 * * % java RandomInt 1000 * Your random integer is: 333 * ******************************************************************************/ public class RandomInt { public static void main(String[] args) { // a positive integer int n = Integer.parseInt(args[0]); // a pseudo-random real between 0.0 and 1.0 double r = Math.random(); // a pseudo-random integer between 0 and n-1 int value = (int) (r * n); System.out.println(value); } }/****************************************************************************** * Compilation: javac Flip.java * Execution: java Flip * * Simulate a fair coin flip and print out "Heads" or "Tails" accordingly. * * % java Flip * Heads * * % java Flip * Heads * * % java Flip * Tails * * ******************************************************************************/ public class Flip { public static void main(String[] args) { // Math.random() returns a value between 0.0 and 1.0 // so it is heads or tails 50% of the time if (Math.random() < 0.5) System.out.println("Heads"); else System.out.println("Tails"); } }
8.while循环/****************************************************************************** * Compilation: javac TenHellos.java * Execution: java TenHellos * * Prints ith Hello for i = 1 to 10. Illlustrates using a while loop * for a repetitive task. * * % java TenHellos * 1st Hello * 2nd Hello * 3rd Hello * 4th Hello * 5th Hello * 6th Hello * 7th Hello * 8th Hello * 9th Hello * 10th Hello * ******************************************************************************/ public class TenHellos { public static void main(String[] args) { // print out special cases whose ordinal doesn't end in th System.out.println("1st Hello"); System.out.println("2nd Hello"); System.out.println("3rd Hello"); // count from i = 4 to 10 int i = 4; while (i <= 10) { System.out.println(i + "th Hello"); i = i + 1; } } }
9.for循环/****************************************************************************** * Compilation: javac DivisorPattern.java * Execution: java DivisorPattern n * * Prints a table where entry (i, j) is a '* ' if i divides j * or j divides i and '. ' otherwise. * * * % java DivisorPattern 20 * * * * * * * * * * * * * * * * * * * * * 1 * * * * * * * * * * * * 2 * * * * * * * * 3 * * * * * * * * 4 * * * * * * 5 * * * * * * * 6 * * * * 7 * * * * * * 8 * * * * * 9 * * * * * * 10 * * * 11 * * * * * * * 12 * * * 13 * * * * * 14 * * * * * 15 * * * * * * 16 * * * 17 * * * * * * * 18 * * * 19 * * * * * * * 20 * ******************************************************************************/ public class DivisorPattern { public static void main(String[] args) { int n = Integer.parseInt(args[0]); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i % j == 0 || j % i == 0) { System.out.print("* "); } else { System.out.print(" "); } } System.out.println(i); } } } 10.for循环/****************************************************************************** * Compilation: javac HarmonicNumber.java * Execution: java HarmonicNumber n * * Prints the nth harmonic number: 1/1 + 1/2 + ... + 1/n. * * % java HarmonicNumber 10 * 2.9289682539682538 * * % java HarmonicNumber 10000 * 9.787606036044348 * ******************************************************************************/ public class HarmonicNumber { public static void main(String[] args) { // command-line argument int n = Integer.parseInt(args[0]); // compute 1/1 + 1/2 + 1/3 + ... + 1/n double sum = 0.0; for (int i = 1; i <= n; i++) { sum += 1.0 / i; } // print the nth harmonic number System.out.println(sum); } }
11.数学函数->abs/****************************************************************************** * Compilation: javac Sqrt.java * Execution: java Sqrt c * * Computes the square root of a nonnegative number c using * Newton's method: * - initialize t = c * - replace t with the average of c/t and t * - repeat until desired accuracy reached * * % java Sqrt 2 * 1.414213562373095 * * % java Sqrt 1000000 * 1000.0 * * % java Sqrt 0.4 * 0.6324555320336759 * * % java Sqrt 1048575 * 1023.9995117186336 * * % java Sqrt 16664444 * 4082.2106756021303 * * % java Sqrt 0 * 0.0 * * % java Sqrt 1e-50 * 9.999999999999999E-26 * * * Remarks * ---------- * - using Math.abs() is required if c < 1 * * * Known bugs * ---------- * - goes into an infinite loop if the input is negative * ******************************************************************************/ public class Sqrt { public static void main(String[] args) { // read in the command-line argument double c = Double.parseDouble(args[0]); double epsilon = 1e-15; // relative error tolerance double t = c; // estimate of the square root of c // repeatedly apply Newton update step until desired precision is achieved while (Math.abs(t - c/t) > epsilon*t) { t = (c/t + t) / 2.0; } // print out the estimate of the square root of c System.out.println(t); } } 12.将十进制转换成二进制13.对数据的处理功能/****************************************************************************** * Compilation: javac Binary.java * Execution: java Binary n * * Prints out n in binary. * * % java Binary 5 * 101 * * % java Binary 106 * 1101010 * * % java Binary 0 * 0 * * % java Binary 16 * 10000 * * Limitations * ----------- * Does not handle negative integers. * * Remarks * ------- * could use Integer.toBinaryString(N) instead. * ******************************************************************************/ public class Binary { public static void main(String[] args) { // read in the command-line argument int n = Integer.parseInt(args[0]); // set power to the largest power of 2 that is <= n int power = 1; while (power <= n/2) { power *= 2; } // check for presence of powers of 2 in n, from largest to smallest while (power > 0) { // power is not present in n if (n < power) { System.out.print(0); } // power is present in n, so subtract power from n else { System.out.print(1); n -= power; } // next smallest power of 2 power /= 2; } System.out.println(); } }/****************************************************************************** * Compilation: javac Gambler.java * Execution: java Gambler stake goal N * * Simulates a gambler who start with $stake and place fair $1 bets * until she goes broke or reach $goal. Keeps track of the number of * times she wins and the number of bets she makes. Run the experiment N * times, averages the results, and prints them out. * * % java Gambler 50 250 1000 * 178 wins of 1000 * Percent of games won = 17.8 * Avg # bets = 10010.79 * * % java Gambler 50 150 1000 * 337 wins of 1000 * Percent of games won = 33.7 * Avg # bets = 4863.95 * * % java Gambler 50 100 1000 * 503 wins of 1000 * Percent of games won = 50.3 * Avg # bets = 2464.59 * ******************************************************************************/ public class Gambler { public static void main(String[] args) { int stake = Integer.parseInt(args[0]); // gambler's stating bankroll int goal = Integer.parseInt(args[1]); // gambler's desired bankroll int trials = Integer.parseInt(args[2]); // number of trials to perform int bets = 0; // total number of bets made int wins = 0; // total number of games won // repeat trials times for (int t = 0; t < trials; t++) { // do one gambler's ruin simulation int cash = stake; while (cash > 0 && cash < goal) { bets++; if (Math.random() < 0.5) cash++; // win $1 else cash--; // lose $1 } if (cash == goal) wins++; // did gambler go achieve desired goal? } // print results System.out.println(wins + " wins of " + trials); System.out.println("Percent of games won = " + 100.0 * wins / trials); System.out.println("Avg # bets = " + 1.0 * bets / trials); } }
14.打印一个数的所有约数
/****************************************************************************** * Compilation: javac Factors.java * Execution: java Factors n * * Computes the prime factorization of n using brute force. * * % java Factors 81 * The prime factorization of 81 is: 3 3 3 3 * * % java Factors 168 * The prime factorization of 168 is: 2 2 2 3 7 * * % java Factors 4444444444 * The prime factorization of 4444444444 is: 2 2 11 41 271 9091 * * % java Factors 4444444444444463 * The prime factorization of 4444444444444463 is: 4444444444444463 * * % java Factors 10000001400000049 * The prime factorization of 10000001400000049 is: 100000007 100000007 * * % java Factors 1000000014000000049 * The prime factorization of 1000000014000000049 is: 1000000007 1000000007 * * % java Factors 9201111169755555649 * The prime factorization of 9201111169755555649 is: 3033333343 3033333343 * * Can use these for timing tests - biggest 3, 6, 9, 12, 15, and 18 digit primes * % java Factors 997 * % java Factors 999983 * % java Factors 999999937 * % java Factors 999999999989 * % java Factors 999999999999989 * % java Factors 999999999999999989 * * Remarks * ------- * - Tests factor*factor <= n instead of factor <= n for efficiency. * * - The last two examples still take a few minutes. * ******************************************************************************/ public class Factors { public static void main(String[] args) { // command-line argument long n = Long.parseLong(args[0]); System.out.print("The prime factorization of " + n + " is: "); // for each potential factor for (long factor = 2; factor*factor <= n; factor++) { // if factor is a factor of n, repeatedly divide it out while (n % factor == 0) { System.out.print(factor + " "); n = n / factor; } } // if biggest factor occurs only once, n > 1 if (n > 1) System.out.println(n); else System.out.println(); } }
15.数组/****************************************************************************** * Compilation: javac Sample.java * Execution: java Sample m n * * This program takes two command-line arguments m and n and produces * a random sample of m of the integers from 0 to n-1. * * % java Sample 6 49 * 10 20 0 46 40 6 * * % java Sample 10 1000 * 656 488 298 534 811 97 813 156 424 109 * ******************************************************************************/ public class Sample { public static void main(String[] args) { int m = Integer.parseInt(args[0]); // choose this many elements int n = Integer.parseInt(args[1]); // from 0, 1, ..., n-1 // create permutation 0, 1, ..., n-1 int[] perm = new int[n]; for (int i = 0; i < n; i++) perm[i] = i; // create random sample in perm[0], perm[1], ..., perm[m-1] for (int i = 0; i < m; i++) { // random integer between i and n-1 int r = i + (int) (Math.random() * (n-i)); // swap elements at indices i and r int t = perm[r]; perm[r] = perm[i]; perm[i] = t; } // print results for (int i = 0; i < m; i++) System.out.print(perm[i] + " "); System.out.println(); } }
16.boolean类型数组/****************************************************************************** * Compilation: javac CouponCollector.java * Execution: java CouponCollector n * * Given n distinct card types, how many random cards do you need * do collect before you have (at least) one of each type? * This program simulates this random process. * * * % java CouponCollector 1000 * 6583 * * % java CouponCollector 1000 * 6477 * * % java CouponCollector 1000000 * 12782673 * ******************************************************************************/ public class CouponCollector { public static void main(String[] args) { int n = Integer.parseInt(args[0]); // number of card types boolean[] isCollected = new boolean[n]; // isCollected[i] = true if card i has been collected int count = 0; // total number of cards collected int distinct = 0; // number of distinct cards // repeatedly choose a random card and check whether it's a new one while (distinct < n) { int value = (int) (Math.random() * n); // random card between 0 and n-1 count++; // we collected one more card if (!isCollected[value]) { distinct++; isCollected[value] = true; } } // print the total number of cards collected System.out.println(count); } }17.数组/****************************************************************************** * Compilation: javac PrimeSieve.java * Execution: java -Xmx1100m PrimeSieve n * * Computes the number of primes less than or equal to n using * the Sieve of Eratosthenes. * * % java PrimeSieve 25 * The number of primes <= 25 is 9 * * % java PrimeSieve 100 * The number of primes <= 100 is 25 * * % java -Xmx100m PrimeSieve 100000000 * The number of primes <= 100000000 is 5761455 * * % java PrimeSieve -Xmx1100m 1000000000 * The number of primes <= 1000000000 is 50847534 * * * The 110MB and 1100MB is the amount of memory you want to allocate * to the program. If your computer has less, make this number smaller, * but it may prevent you from solving the problem for very large * values of n. * * * n Primes <= n * --------------------------------- * 10 4 * 100 25 * 1,000 168 * 10,000 1,229 * 100,000 9,592 * 1,000,000 78,498 * 10,000,000 664,579 * 100,000,000 5,761,455 * 1,000,000,000 50,847,534 * ******************************************************************************/ public class PrimeSieve { public static void main(String[] args) { int n = Integer.parseInt(args[0]); // initially assume all integers are prime boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) { isPrime[i] = true; } // mark non-primes <= n using Sieve of Eratosthenes for (int factor = 2; factor*factor <= n; factor++) { // if factor is prime, then mark multiples of factor as nonprime // suffices to consider mutiples factor, factor+1, ..., n/factor if (isPrime[factor]) { for (int j = factor; factor*j <= n; j++) { isPrime[factor*j] = false; } } } // count primes int primes = 0; for (int i = 2; i <= n; i++) { if (isPrime[i]) primes++; } System.out.println("The number of primes <= " + n + " is " + primes); } }18.二维数组/****************************************************************************** * Compilation: javac SelfAvoidingWalk.java * Execution: java SelfAvoidingWalk n trials * * Generate trials self-avoiding walks of length n. * Report the fraction of time the random walk is non self-intersecting. * ******************************************************************************/ public class SelfAvoidingWalk { public static void main(String[] args) { int n = Integer.parseInt(args[0]); // lattice size int trials = Integer.parseInt(args[1]); // number of trials int deadEnds = 0; // trials resulting in a dead end // simulate trials self-avoiding walks for (int t = 0; t < trials; t++) { boolean[][] a = new boolean[n][n]; // intersections visited int x = n/2, y = n/2; // current position // repeatedly take a random step, unless you've already escaped while (x > 0 && x < n-1 && y > 0 && y < n-1) { // dead-end, so break out of loop if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1]) { deadEnds++; break; } // mark (x, y) as visited a[x][y] = true; // take a random step to unvisited neighbor double r = Math.random(); if (r < 0.25) { if (!a[x+1][y]) x++; } else if (r < 0.50) { if (!a[x-1][y]) x--; } else if (r < 0.75) { if (!a[x][y+1]) y++; } else if (r < 1.00) { if (!a[x][y-1]) y--; } } } System.out.println(100*deadEnds/trials + "% dead ends"); } }