Java Programming Tutorial
Java Programming Tutorial
program
called CheckPassFail which prints "PASS" if the intvariable "mark" is more than or
program
called CheckOddEven which prints "Odd Number" if the int variable number is odd, or Even Number otherwise. Hints: n is an even number if (n % 2) is 0.
public class CheckOddEven { // saved as "CheckOddEven.java" public static void main(String[] args) { int number = 49; // set the value of number here! System.out.println("The number is " + number); if ( ...... ) { System.out.println( ...... ); } else { System.out.println( ...... ); } } }
switch-case): Write
program called PrintNumberInWord which prints "ONE", "TWO",... , "NINE", "OTHER" if the int variable "number" is 1, 2,... , 9, or other, respectively. Use (a) a "nested-if" statement; (b) a "switch-case" statement. Hints:
public class PrintNumberInWord { // saved as "PrintNumberInWord.java" public static void main(String[] args) { int number = 5; // Using nested-if if (number == 1) { System.out.println("ONE"); } else if (......) { ...... } else if (......) { ...... ...... } else { ...... } // Using switch-case switch(number) { case 1: System.out.println("ONE"); break; case 2: ...... ...... ...... default: System.out.println("OTHER"); } } }
Similarly, write a program called PrintDayInWord, which prints Sunday, Monday, ... Saturday if the int variable "day" is 0, 1, ..., 6, respectively. Otherwise, it shall print Not a valid day.
Hints:
public class SumAndAverage { // saved as "SumAndAverage.java" public static void main (String[] args) { int sum = 0; // store the accumulated sum, init to 0 double average; // average in double int lowerbound = 1; // the lower bound to sum int upperbound = 100; // the upper bound to sum for (int number = lowerbound; number <= upperbound; number++) { // for loop sum += number; // same as "sum = sum + number" } // Compute average in double. Beware that int/int produces int. ......
TRY: 1.
2. 3. 4. 5. 6. }
7.
8. 9. 10. 11. 12.
13.
What is the difference between "for" and "while-do" loops? What is the
14. Modify the program to sum from 111 to 8899, and compute the average. Introduce an int variable called count to count the numbers in the specified range. 15.
16. 17. 18. } int count = 0; // count the number within the range, init to 0 for (...; ...; ...) { ...... count++;
19. Modify the program to sum only the odd numbers from 1 to 100, and compute the average. (Hint: n is an odd number if n % 2 is not 0.)
20. Modify the program to sum those numbers from 1 to 100 that is divisible by 7, and compute the average. 21. Modify the program to find the "sum of the squares" of all the numbers from 1 to 100, i.e. 1*1 + 2*2 + 3*3 + ... + 100*100.
program
called Product1ToN to
product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product obtained and explain the results. Hints: Declares an int variable called product (to accumulate the product) and initialize to 1.
Hints:
public class HarmonicSum { // saved as "HarmonicSum.java" public static void main (String[] args) { int maxDenominator = 50000; double sumL2R = 0.0; // sum from left-to-right double sumR2L = 0.0; // sum from right-to-left // for-loop for summing from left-to-right for (int denominator = 1; denominator <= maxDenominator; denominator++) { ...... // Beware that int/int gives int. } // for-loop for summing from right-to-left ...... // Find the difference and display ...... } }
&
Condition): Write
program
called ComputePI to compute the value of , using the following series expansion. You have to decide on the termination criterion used in the computation (such as the number of terms used or the magnitude of an additional term). Is this series suitable for computing ?
JDK maintains the value of in a double constant called Math.PI. Compare the values obtained and the Math.PI, in percents of Math.PI. Hint: Add to sum if the denominator modulus 4 is 1, and subtract from sum if it is 3.
double sum = 0;
int maxDenom = 10000000; for (int denom = 1; ..... ; denom = denom + 2) { if (denom % 4 == 1) { sum += ......; } else if (denom % 4 == 3) { sum -= ......; } else { System.out.println("The computer has gone crazy?!"); } }
&
Condition): Write
program
called CozaLozaWoza which prints the numbers 1 to 110, 11 numbers per line. The program shall print "Coza" in place of the numbers which are multiples of 3, "Loza" for multiples of 5, "Woza" for multiples of 7, "CozaLoza" for multiples of 3 and 5, and so on. The output shall look like:
1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11 Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22 23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza ......
Hints:
public class CozaLozaWoza { // saved as "CozaLozaWoza.java" public static void main(String[] args) { int lowerbound = 1; int upperbound = 110; for (int number = lowerbound; number <= upperbound; number++) { // Print "Coza" if number is divisible by 3 if (......) { System.out.print("Coza"); } // Print "Loza" if number is divisible by 5 if (......) { System.out.print(.....); } // Print "Woza" if number is divisible by 7 ...... // Print the number if it is not divisible by 3, 5 and 7 if (......) { ...... } // Print a space ...... // Print a newline if number is divisible by 11
if (......) { System.out.println(); } } } }
TRY: Modify the program to use nested-if (if ... else if ... else if ... else) instead.
Hints:
public class Fibonacci { public static void main (String args[]) { int n = 3; // the index n for F(n), starting from n=3 int fn; // F(n) to be computed int fnMinus1 = 1; // F(n-1), init to F(2) int fnMinus2 = 1; // F(n-2), init to F(1) int nMax = 20; // maximum n, inclusive int sum = fnMinus1 + fnMinus2; double average; System.out.println("The first " + nMax + " Fibonacci numbers are:"); ...... while (n <= nMax) { // Compute F(n), print it and add to sum ...... // Adjust the index n and shift the numbers ...... } // Compute and display the average (=sum/nMax) ...... } }
Tribonacci numbers are a sequence of numbers T(n) similar to Fibonacci numbers, except that a number is formed by adding the three previous numbers, i.e., T(n)=T(n1)+T(n-2)+T(n-3), T(1)=T(2)=1, and T(3)=2. Write a program called Tribonacci to
program
called SquareBoard that displays the following nn (n=5) pattern using two nested
Your program should use only two output statements, one EACH of the followings:
System.out.print("# "); // print # and a space, without newline System.out.println(); // print a newline
Hints:
public class SquareBoard { // saved as "SquareBoard.java" public static void main (String[] args) { int size = 5; // size of the board for (int row = 1; ......; ......) { for (int col = 1; ......; ......) { ...... } ...... } } }
program
called CheckerBoard that displays the following nn (n=7) checkerboard pattern using two nested for-loops.
####### ####### ####### ####### ####### ####### #######
Your program should use only three output statements, one EACH of the followings:
System.out.print("# "); // print # and a space, without newline System.out.print(" "); // print a space, without newline System.out.println(); // print a newline
Hints:
public class CheckerBoard { // saved as "CheckerBoard.java" public static void main (String[] args) { int size = 7; // size of the board for (int row = 1; ......; ......) { // Use modulus 2 to find alternate lines if ((row % 2) == 0) { // row 2, 4, 6, 8 ...... } for (int col = 1; ......; ......) { ...... } ...... } } }
Input): Write
program
called KeyboardScanner to prompt user for an int, a double, and a String. The output
Hints:
import java.util.Scanner; // needed to use Scanner for input public class KeyboardScanner {
public static void main(String[] args) { int num1; double num2; String name; double sum; // Setup a Scanner called in to scan the keyboard (System.in) Scanner in = new Scanner(System.in); System.out.print("Enter an integer: "); num1 = in.nextInt(); // use nextInt() to read int System.out.print("Enter a floating point number: "); num2 = in.nextDouble(); // use nextDouble() to read double System.out.print("Enter your name: "); name = in.next(); // use next() to read String // Display ...... } }
You need to create a text file called "in.txt" (in Eclipse, right-click on the "project" "New" "File") with the following contents:
12 33.44 Peter import java.util.Scanner; // Needed to use Scanner for input import java.io.File; // Needed to use File import java.io.FileNotFoundException; // Needed for file operation public class FileScanner { public static void main(String[] args) throws FileNotFoundException { // Needed for file operation int num1; double num2; String name; double sum; // Setup a Scanner to read from a text file Scanner in = new Scanner(new File("in.txt"));
num1 = in.nextInt(); // use nextInt() to read int num2 = in.nextDouble(); // use nextDouble() to read double name = in.next(); // use next() to read String // Display ...... } }
Input): Write
program
called CircleComputation, which prompts user for a radius (of double) and compute the area and perimeter of a circle. The output shall look like:
Enter the radius: 1.2 The area is 4.5239 The perimeter is 7.5398223686155035
3. Exercises Operations
on
User
Input
and
String
Hints:
import java.util.Scanner; public class ReverseString { public static void main(String[] args) { String inStr; // input String int inStrLen; // length of the input String Scanner in = new Scanner(System.in); System.out.print("Enter a String: "); inStr = in.next(); // use next() to read String inStrLen = inStr.length(); // Use inStr.charAt(index) to extract character at 'index' from inStr ...... } }
For a String called inStr, you can use inStr.length() to get the length of the String; and inStr.charAt(index) to retrieve the char at theindex position, where index begins with 0.
Write a program called PhoneKeyPad, which prompts user for a String (case insensitive), and converts to a sequence of digits. Use a nested-if (or switch-case) in this exercise. Modify your program to use an array for table look-up later. Hints: You can use in.next().toLowerCase() to read a string and convert it to lowercase to reduce your cases.
Hints: For a n-bit binary number bn-1bn-2...b1b0, bi{0,1}, the equivalent decimal number is bn-12n-1+bn-22n-2+ ...+b121+b020.
import java.util.Scanner; public class Bin2Dec { public static void main(String[] args) { String binStr; // input binary string int binStrLen; // length of the input string int dec = 0; // equivalent decimal number char binChar; // each individual char in the binary string Scanner in = new Scanner(System.in); // Read input binary string ...... // Convert binary string into Decimal ...... } } binStr :10111001
charAt(idx)
:01234567
Math.pow(2, order) : 7 6 5 4 3 2 1 0
You can use JDK method Math.pow(x, y) to compute the x raises to the power of y. This method takes two doubles as argument and returns adouble. You may have to cast the result back to int. To convert a char (of digit '0' to '9') to int (0 to 9), simply subtract by char '0', e.g., '5'-'0' gives int 5.
Hints: For a n-digit hexadecimal number hn-1hn-2...h1h0, hi{0,,9,A,,F}, the equivalent decimal number is hn-116n-1+hn-216n-2+ ...+h1161+h0160. You do not need a big nested-if statement of 16 cases (or 22 considering the upper and lower letters). Extract the individual character from the hexadecimal string, says c. If char c is between '0' to '9', you can get the integer offset via c-'0'. If c is between 'a' to 'f' or 'A' to 'F', the integer offset is c-'a'+10 or c-'A'+10.
String hexStr; char hexChar; ...... hexChar = hexStr.charAt(i); ...... if (hexChar >= '0' && hexChar <= '9') { ... (hexChar-'0') ... ... } else if (hexChar >= 'a' && hexChar <= 'f') { // lowercase ... (hexChar-'a'+10) ... ... } else if (hexChar >= 'A' && hexChar <= 'F') { // uppercase ... (hexChar-'A'+10) ... ... } else { System.out.println("Error: Invalid hexadecimal string");
System.exit(1); }
4. Exercises on Array
Exercise GradesAverage (Array): Write a program called GradesAverage,
which prompts user for the number of students, reads it from the keyboard, and saves it in an int variable called numStudents. It then prompts user for the grades of each of the students and saves them in an intarray called grades. Your program shall check that the grade is between 0 and 100. A sample session is as follow:
Enter the number of students: 3 Enter the grade for student 1: 55 Enter the grade for student 2: 108 Invalid grade, try again... Enter the grade for student 2: 56 Enter the grade for student 3: 57 The average is 56.0
and
Table
Lookup): Write
program
called Hex2Bin to convert a hexadecimal string into its equivalent binary string. The output shall look like:
Enter a Hexadecimal string: 1abc The equivalent binary for hexadecimal "1abc" is 0001 1010 1011 1100
16
binary Strings
corresponding
to
hexadecimal
String[] hexBits = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}
Hints:
The method main(String[] args) takes an argument: "an array of String", which is often (but not necessary) named args. This parameter captures the command-line arguments supplied by the user when the program is invoked. For example, if a user invokes:
> java Arithmetic 12345 4567 +
The three command-line arguments "12345", "4567" and "+" will be captured in a String array {"12345", "4567", "+"} and passed into themain() method as the argument args. That is,
args is {"12345", "4567", "+"}; // args is a String array args.length is 3; // length of the array args[0] is "12345"; // 1st element of the String array args[1] is "4567"; // 2nd element of the String array args[2] is "+"; // 3rd element of the String array args[0].length() is 5; // length of 1st String element args[1].length() is 4; // length of the 2nd String element args[2].length() is 1; // length of the 3rd String element public class Arithmetic { public static void main (String[] args) { int operand1, operand2; char theOperator; // Check if there are 3 command-line arguments in the // String array args[] by using length variable of array. if (args.length != 3) { System.err.println("Usage: java Arithmetic int1 int2 op"); return; } // Convert the 3 Strings args[0], args[1], args[2] to int and char. // Use the Integer.parseInt(aStr) to convert a String to an int. operand1 = Integer.parseInt(args[0]); operand2 = ...... // Get the operator, assumed to be the first character of // the 3rd string. Use method charAt() of String. theOperator = args[2].charAt(0); System.out.print(args[0] + args[2] + args[1] + "="); switch(theOperator) { case ('-'): System.out.println(operand1 operand2); break; case ('+'): ...... case ('*'): ...... case ('/'): ...... default: System.err.println("Error: invalid operator!"); } } }
Notes:
To provide command-line arguments, use the "cmd" shell to run your program
"Run As" "Run Configurations..." Select "Main" and choose the proper main class Select "Arguments" Enter the command-line arguments, e.g., "3 2 +" in "Program Arguments".
To provide command-line arguments in Netbeans, right click the "Project"
name "Set Configuration" "Customize..." Select categories "Run" Enter the command-line arguments, e.g., "3 2 +" in the "Arguments" box (but make sure you select the proper Main class). Question: Try "java Arithmetic 2 4 *" (in CMD shell and Eclipse/Netbeans) and explain the result obtained. How to resolve this problem? In Windows' CMD shell, * is known as a wildcard character, that expands to give the list of file in the directory (called Shell Expansion). For example, "dir *.java" lists all the file with extension of ".java". You could double-quote the * to prevent shell expansion. Eclipse has a bug in handling this, even * is double-quoted. NetBeans??
arguments): Write
program
called SumDigits to sum up the individual digits of a positive integer, given in the command line. The output shall look like:
> java SumDigits 12345 The sum of digits = 1 + 2 + 3 + 4 + 5 = 15
6. Exercises on Method
Exercise GradesStatistics (Method): Write
called GradesStatistics, which reads in n grades a program (of int between 0 and 100, inclusive) and displays the average, minimum, maximum, and standard deviation. Your program shall check for valid input. You should keep the grades in an int[] and use a method for each of the computations. Your output shall look like:
Enter the number of students: 4 Enter the grade for student 1: 50 Enter the grade for student 2: 51 Enter the grade for student 3: 56 Enter the grade for student 4: 53 The average is 52.5 The minimum is 50 The maximum is 56 The standard deviation is 2.29128784747792
public class GradesStatistics { public static int[] grades; // Declare an int[], to be allocated later
// main() method public static void main(String[] args) { readGrades(); System.out.println("The average is " + average()); System.out.println("The minimum is " + min()); System.out.println("The maximum is " + max()); System.out.println("The standard deviation is " + stdDev()); } // Prompt user for the number of students and allocate the "grades" array. // Then, prompt user for grade, check for valid grade, and store in "grades". public static void readGrades() { ....... } // Return the average value of int[] grades public static double average() { ...... } // Return the maximum value of int[] grades public static int max() { ...... } // Return the minimum value of int[] grades public static int min() { ....... } // Return the standard deviation of the int[] grades public static double stdDev() { ....... } }
program
called GradesHistogram, which reads in n grades (of int between 0 and 100, inclusive) from a text file called "grades.in" and displays the histogram horizontally and vertically. The file has the following format:
numStduents:int grade1:int grade2:int .... gradeN:int
For example:
15 49 50 51 59 0 5 9 10 15 19 50 55 89 99 100
The output shall consist of a horizontal histogram and a vertical histogram as follows:
0 - 9: *** 10 - 19: *** 20 - 29: 30 - 39: 40 - 49: * 50 - 59: *****
* * * * * * * * * * * * * * *
0-9 10-19 20-29 30-39 40-49 50-59 60-69 70-79 80-89 90-100
Hints:
public class GradesHistogram { public static int[] grades; // Declare an int array of grades, to be allocated later public static int[] bins = new int[10]; // Declare and allocate an int array for histogram bins. // 10 bins for 0-9, 10-19,...., 90-100 public static void main(String[] args) { readGrades("grades.in"); computeHistogram(); printHistogramHorizontal(); printHistogramVertical(); } // Read the grades from "filename", store in "grades" array. // Assume that the inputs are valid. public static void readGrades(String filename) { ...... } // Based on "grades" array, populate the "bins" array. public static void computeHistogram() { ....... } // Print histogram based on the "bins" array. public static void printHistogramHorizontal() { ...... } // Print histogram based on the "bins" array. public static void printHistogramVertical() { ...... } }
method
The method accepts an int array, and reverses its orders. For example, if the input array is {12, 56, 34, 79, 26}, the reversal is {26, 79, 34, 56, 12}. You MUST NOT use another array in your method (but you need a temporary variable to do the swap). Also write a test class calledReverseArrayTest to test this method. Take note that the array passed into the method can be modified by the method (this is called "pass by reference"). On the other hand, primitives passed into a method cannot be modified. This is because a clone is created and passed into the method instead of the original copy (this is called "pass by value").
Exercise Matrix: Similar to Math class, write a Matrix library that supports matrix
operations (such as addition, subtraction, multiplication) via 2D arrays. The operations shall support both doubles and ints. Also write a test class to exercise all the operations programmed. Hints:
public class Matrix { public static void printMatrix(int[][] m) { ...... } public static void printMatrix(double[][] m) { ...... } public static boolean haveSameDimension(int[][] m1, int[][] m2) { ...... } public static boolean haveSameDimension(double[][] m1, double[][] m2) { ...... } public static int[][] add(int[][] m1, int[][] m2) { ...... } public static double[][] add(double[][] m1, double[][] m2) { ...... } ...... }
Exercise PrintAnimalPattern (Special Characters and Escape Sequences): Write a program called PrintAnimalPattern, which usesprintln() to
produce this pattern:
'__' () /========\/ / || %% || * ||----|| "" ""
Hints:
Use escape sequence \uhhhh where hhhh are four hex digits to display
Unicode characters such as and . is 165 (00A5H) and is 169 (00A9H) in both ISO-8859-1 (Latin-1) and Unicode character sets. Double-quote (") and black-slash (\) require escape sign inside a String. Single quote (') does not require escape sign. TRY: Print the same pattern using printf(). (Hints: Need to use %% to print a % in printf() because % is the suffix for format specifier.)
Hints: On the diagonal, row = col. On the opposite diagonal, row + col = size + 1.
####### # # # # # # # # # # # #
####### # # # # #
####### # # ##
####### ##
#######
# # # # # # #
# # # # # # #
# # #
# # # # ## ## ####### #######
####### (g)
#########
# (j)
########### (k)
###########
12345678 (m)
1 21 321
123456787654321 1234567 7654321 123456 12345 1234 123 12 1 (t) 654321 54321 4321 321 21 1
Write the main() which prompts the user for the numRows and prints all the patterns.
1 1 2 1 1 2 4 2 1 1 2 4 8 4 2 1 1 2 4 8 16 8 4 2 1 1 2 4 8 16 32 16 8 4 2 1 1 2 4 8 16 32 64 32 16 8 4 2 1 1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 (a) PowerOf2Triangle
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 (b) PascalTriangle1
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 (c) PascalTriangle2
method
to
compute sin(x) and cos(x) using the following series expansion, calledTrigonometricSeries. The headers of the methods are:
public static double sin(double x, int numTerms) // x in radians public static double cos(double x, int numTerms)
in
class
Compare
the
values
computed
using
the
series
with
the numbers
JDK of
various
Hints: Avoid generating large numerator and denominator (which may cause arithmetic overflow, e.g., 13! is out of int range). Compute the terms as:
Hints: The maximum and minimum values of constants Integer.MAX_VALUE and Integer.MIN_VALUE, statements:
System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); System.out.println(Integer.MAX_VALUE + 1);
Take note that in the third statement, Java Runtime does not flag out an overflow error, but silently wraps the number around. Hence, you cannot useF(n-1) + F(n-2) >
Integer.MAX_VALUE to
check for overflow. Instead, overflow occurs for F(n) if (Integer.MAX_VALUE F(n-1)) < F(n-2)(i.e., no room for the next Fibonacci number). Write a similar program for Tribonacci numbers.
Modify your program (called FactorialInt), to list all the factorials, that can be expressed as an int (i.e., 32-bit signed integer). Your output shall look like:
The factorial of 1 is 1 The factorial of 2 is 2 ... The factorial of 12 is 479001600 The factorial of 13 is out of range
Hints: Overflow occurs for Factorial(n+1) if (Integer.MAX_VALUE / Factorial(n)) < (n+1). Modify your program again (called FactorialLong) to list all the factorials that can be expressed as a long (64-bit signed integer). The maximum value for long is kept in a constant called Long.MAX_VALUE.
Write a program called NumberConversion, which prompts the user for an input number, an input radix, and an output radix, and display the converted number. The output shall look like:
Enter a number and radix: A1B2 Enter the input radix: 16 Enter the output radix: 2 "A1B2" in radix 16 is "1010000110110010" in radix 2.
number guessing game. The program shall generate a random number between 0 and 99. The player inputs his/her guess, and the program shall response with "Try higher", "Try lower" or "You got it in n trials" accordingly. For example:
> java NumberGuess Key in your guess: 50 Try higher 70 Try lower 65 Try lower " You got it in 4 trials!
Hints: Use Math.random() to produce a random number in double between 0.0 and (less than) 1.0. To produce an int between 0 and 99, use:
int secretNumber = (int)(Math.random()*100);
Hints:
Set up a boolean array to indicate the positions of the word that have been
guessed correctly.
Check the length of the input String to determine whether the player enters a
single character or a guessed word. If the player enters a single character, check it against the word to be guessed, and update the boolean array that keeping the result so far.
Try retrieving the word to be guessed from a text file (or a dictionary)
randomly.
boolean
returns true if the given year, month and day constitute a given date. Assume that year is between
isValidDate(int year, int month, int
day):
1 and 9999, month is between 1 (Jan) to 12 (Dec) and day shall be between 1 and 28|29|30|31 depending on the month and whether it is a leap year.
int getDayOfWeek(int year, int month, int day): returns the day of the week,
where 0 for SUN, 1 for MON, ..., 6 for SAT, for the given date. Assume that the date is valid. String toString(int year, int month, int day): prints the given date in the format "xxxday d mmm yyyy", e.g., "Tuesday 14 Feb 2012". Assume that the given date is valid. To find the day of the week (Reference: Wiki "Determination of the day of the week"): 1. Based on the first two digit of the year, get the number from the following "century" table.
1700-
1800-
1900-
2000-
2100-
2200-
4
2. 3. 4. part". 5.
Take note that the entries 4, 2, 0, 6 repeat. Add to the last two digit of the year. Add to "the last two digit of the year divide by 4, truncate the fractional Add to the number obtained from the following month table:
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
0 6
3 2
6 2 same as above
7. The sum modulus 7 gives the day of the week, where 0 for SUN, 1 for MON, ..., 6 for SAT. For example: 2012, Feb, 17
(6 + 12 + 12/4 + 2 + 17) % 7 = 5 (Fri) /* Utilities for Date Manipulation */ public class DateUtil { // Month's name for printing public static String strMonths[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; // Number of days in each month (for non-leap years) public static int daysInMonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Returns true if the given year is a leap year public static boolean isLeapYear(int year) { ...... } // Return true if the given year, month, day is a valid date // year: 1-9999 // month: 1(Jan)-12(Dec) // day: 1-28|29|30|31. The last day depends on year and month public static boolean isValidDate(int year, int month, int day) { ...... } // Return the day of the week, 0:Sun, 1:Mon, ..., 6:Sat public static int getDayOfWeek(int year, int month, int day) { ...... } // Return String "xxxday d mmm yyyy" (e.g., Wednesday 29 Feb 2012) public static String printDate(int year, int month, int day) { ...... } public static void main(String[] args) { System.out.println(isLeapYear(1900)); System.out.println(isLeapYear(2000)); System.out.println(isLeapYear(2011)); System.out.println(isLeapYear(2012));
System.out.println(isValidDate(2012, 2, 29)); // true System.out.println(isValidDate(2011, 2, 29)); // false System.out.println(isValidDate(2099, 12, 31)); // true System.out.println(isValidDate(2099, 12, 32)); // true System.out.println(getDayOfWeek(1982, 4, 24)); // 6:Sat System.out.println(getDayOfWeek(2000, 1, 1)); // 6:Sat System.out.println(getDayOfWeek(2054, 6, 19)); // 5:Fri System.out.println(getDayOfWeek(2012, 2, 17)); // 5:Fri System.out.println(toString(2012, 2, 14)); // Tuesday 14 Feb 2012 } }
You can compare the day obtained with the Java's Calendar class as follows:
// Construct a Calendar instance with the given year, month and day Calendar cal = new GregorianCalendar(year, month - 1, day); // month is 0-based // Get the day of the week number: 1 (Sunday) to 7 (Saturday) int dayNumber = cal.get(Calendar.DAY_OF_WEEK); String[] calendarDays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; // Print result System.out.println("It is " + calendarDays[dayNumber - 1]);
The calendar we used today is known as Gregorian calendar, which came into effect in October 15, 1582 in some countries and later in other countries. It replaces the Julian calendar. 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian). The only difference between the Gregorian and the Julian calendar is the "leap-year rule". In Julian calendar, every four years is a leap year. In Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar
omits century years which are not divisible by 400. Furthermore, Julian calendar considers the first day of the year as march 25th, instead of January 1st. This above algorithm work for Gregorian dates only. It is difficult to modify the above algorithm to handle pre-Gregorian dates. A better algorithm is to find the number of days from a known date.
Exercise
(Prime
Factors): Write
method isProductOfPrimeFactors(int
posInt) that takes a positive integer, and return true if the product of all its prime
factors (excluding 1 and the number itself) is equal to its value. For example, the method returns true for 30 (30=235) and false for 20(2025). You may need to use the isPrime() method in the previous exercise. Write a program called PerfectPrimeFactorList that prompts user for an upper bound. The program shall display all the numbers (less than or equal to the upper bound) that meets the above criteria. The output shall look like:
Enter the upper bound: 100 These numbers are equal to the product of prime factors: 1 6 10 14 15 21 22 26 30 33 34 35 38 39 42 46 51 55 57 58 62 65 66 69 70 74 77 78 82 85 86 87 91 93 94 95 [36 numbers found (36.00%)]
For example,
GCD(15, 5) = GCD(5, 0) = 5 GCD(99,88) = GCD(88,11) = GCD(11,0) = 11 GCD(3456,1233) = GCD(1233,990) = GCD(990,243) = GCD(243,18) = GCD(18,9) = GCD(9,0) = 9
Your methods shall handle arbitrary values of a and b, and check for validity.