java programming
Hello World.java
/************************************************************************* *
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)
{
System.out.println("Hello, World");
}
}
Use Argument.java
/************************************************************************* *
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?");
}
}
Ruler.java
/************************************************************************* *
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);
}
}
Int Ops.java
/************************************************************************* *
Compilation: javac IntOps.java
* Execution: java IntOps a b
* Illustrates the integer operations 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);
}
}
Quadratic.java
/*************************************************************************
*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);
}
}
Leap Year.java
/*************************************************************************
* 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);
}
}
Random Int.java
/*************************************************************************
* 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)
{
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 n = (int) (r * N);
System.out.println("Your random integer is: " + n);
}
}
Flip.java
/*************************************************************************
* 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 it heads or tails 50% of the time
if (Math.random() < 0.5)
System.out.println("Heads");
else
System.out.println("Tails");
}
}
Ten Hellos.java
/*************************************************************************
* 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;
}
}
}
Powers Of Two.java
/*************************************************************************
* Compilation: javac PowersOfTwo.java
* Execution: java PowersOfTwo N
* This program takes a command-line argument N and prnts a table of
* the powers of 2 that are less than or equal to 2^N.
* % java PowersOfTwo 5
* 0 1
* 1 2
* 2 4
* 3 8
* 4 16
* 5 32
* % java PowersOfTwo 6
* 0 1
* 1 2
* 2 4
* 3 8
* 4 16
* 5 32
* 6 64
* Remarks
* ------------
* Only works if 0 <= N < 31 since 2^31 overflows an int.
*
*************************************************************************/
public class PowersOfTwo
{
public static void main(String[] args)
{
// read in one command-line argument int N = Integer.parseInt(args[0]);
int i = 0;
// count from 0 to N-1
int powerOfTwo = 1;
// the ith power of two
// repeat until i equals N
while (i <= N)
{
System.out.println(i + " " + powerOfTwo);
// print out the power of two powerOfTwo = 2 * powerOfTwo;
// double to get the next one i = i + 1;
}
}
}
Divisor Pattern.java
/*************************************************************************
* 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);
}
}
}
Harmonic.java
/*************************************************************************
* Compilation: javac Harmonic.java
* Execution: java Harmonic N
* Prints the Nth harmonic number: 1/1 + 1/2 + ... + 1/N.
* % java Harmonic 10
* 2.9289682539682538
* % java Harmonic 10000
* 9.787606036044348
*
*************************************************************************/
public class Harmonic
{
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 out Nth harmonic number System.out.println(sum);
}
}
Sqrt.java
/*************************************************************************
* 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);
}
}
Binary.java
/*************************************************************************
* 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 v to the largest power of two that is <= n
int v = 1;
while (v <= n/2)
{
v = v * 2;
}
// check for presence of powers of 2 in n, from largest to smallest
while (v > 0)
{
// v is not present in n if (n < v)
{
System.out.print(0);
}
// v is present in n, so remove v from n else
{
System.out.print(1); n = n - v;
}
// next smallest power of 2
v = v / 2;
}
System.out.println();
}
}
Gambler.java
/*************************************************************************
* 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
* Percent of games won = 19.0
* Avg # bets = 9676.302
* % java Gambler 50 150 1000
* Percent of games won = 31.9
* Avg # bets = 4912.13
* % java Gambler 50 100 1000
* Percent of games won = 49.6
* Avg # bets = 2652.352
*
*************************************************************************/
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 T = 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 N times
for (int t = 0; t < T; 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 " + T);
System.out.println("Percent of games won = " + 100.0 * wins / T);
System.out.println("Avg # bets = " + 1.0 * bets / T);
}
}
Factors.java
/*************************************************************************
* 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 i*i <= N instead of i <= 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 i
for (long i = 2; i*i <= n; i++)
{
// if i is a factor of N, repeatedly divide it out
while (n % i == 0)
{
System.out.print(i + " ");
n = n / i;
}
}
// if biggest factor occurs only once, n > 1
if (n > 1)
System.out.println(n); else System.out.println();
}
}