

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Java Programming Tutorial Exercises on Java Basics
Typology: Exams
1 / 25
This page cannot be seen from the preview
Don't miss anything!


















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(...............); } } public class CheckPassFail { // saved as "CheckPassFail.java" public static void main(String[] args) { int mark = 49; // set the value of mark here! System.out.println("The mark is " + mark); if ( ...... ) { System.out.println(...............); } else { System.out.println(...............); } } }
1.1 Exercises on Conditional (Deci 1.2 Exercises on Loop (Iteration) 1.3 Exercises on Nested-Loop
1.1 Exercises on Conditional (Decision)
the int variable "mark" is more than or equal to 50 ; or prints "FAIL" otherwise. Hints:
the int variable “number” is odd, or “Even Number” otherwise. Hints: n is an even number if (n % 2) is
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: 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”. 1.2 Exercises on Loop (Iteration)
3, ..., to an upperbound (e.g., 100). Also compute and display the average. The output shall look like: 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. ...... // Print sum and average. public class PrintNumberInWord { // saved as "PrintNumberInWord.java" public static void main(String[] args) { int number = 5; // Using nested- if if (number ==
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 ...... } }
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?!"); } }
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.
numbers F(n), where F(n)=F(n–1)+F(n–2) and F(1)=F(2)=1. Also compute their average. The output shall look like: The first 20 Fibonacci numbers are: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 The average is 885. Hints: public class Fibonacci { public static void main (String args[]) { int n = 3; // the index n for F(n), starting from n= 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
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; ......; ......) { ...... } ...... } } }
multiplication table of 1 to 9 as shown using two nested for-loops:
2. Exercises on Keyboard and File Input
prompt user for an int, a double, and a String. The output shall look like (the inputs are shown in bold): Enter an integer: 12 Enter a floating point number: 33. Enter your name: Peter Hi! Peter, the sum of 12 and 33.44 is 45. 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 ...... } }
double, and a String form a text file called "in.txt", and produce the following output: The integer read is 12 The floating point number read is 33.44 The String read is "Peter" Hi! Peter, the sum of 12 and 33.44 is 45. You need to create a text file called "in.txt" (in Eclipse, right-click on the "project" ⇒ "New" ⇒ "File") with the following contents: 12
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 ...... } }
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. The area is 4. The perimeter is 7.
The equivalent decimal number for binary "1011" is 11 Enter a Binary string: 1234 Error: Invalid Binary String "1234" Hints: For a n-bit binary number bn-1bn-2...b 1 b 0 , bi∈{0,1}, the equivalent decimal number is bn-1× n- (^1) +b n-2× n-2+ ...+b 1 × 1 +b 0 × 0 . 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 : 1 0 1 1 1 0 0 1 charAt(idx) : 0 1 2 3 4 5 6 7 Math.pow(2, order) : 7 6 5 4 3 2 1 0 binStr.length() = 8 idx + order = binStr.length() - 1 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 a double. 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.
equivalent decimal number. Your output shall look like: Enter a Hexadecimal string: 1a The equivalent decimal number for hexadecimal "1a" is 26 Enter a Hexadecimal string: 1y Error: Invalid Hexadecimal String "1y3" Hints: For a n-digit hexadecimal number hn-1hn-2...h 1 h 0 , hi∈{0,…,9,A,…,F}, the equivalent decimal number is hn-1×16n-^1 +hn-2×16n-2+ ...+h 1 ×16^1 +h 0 ×16^0. 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); // quit the program }
4. Exercises on Array
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 int array 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.
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 Hints: Use an array of 16 binary Strings corresponding to hexadecimal number '0' to 'F', as follows: String[] hexBits = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}
5. Exercises on Command-line Arguments
takes three command-line arguments: two integers followed by an arithmetic operator (+, - , * or /). The program shall perform the corresponding operation on the two integers and print the result. For example: > java Arithmetic 3 2 + 3+2= > java Arithmetic 3 2 - 3-2=
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??
up the individual digits of a positive integer, given in the command line. The output shall look like:
6. Exercises on Method
in n grades (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: Hints: The formula for calculating standard deviation is: 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 > java SumDigits 12345 The sum of digits = 1 + 2 + 3 + 4 + 5 = 15 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. The minimum is 50 The maximum is 56
// 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() {.........} }
signature: public static void reverseArray(int[] intArray) 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 called ReverseArrayTest 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 ").
7. More (Diffi cult) Exercises
⇒ "src.zip" ⇒ "Math.java" under folder "java.lang"). Study how constants such as E and PI are defined. Also study how methods such as abs(), max(), min(), toDegree(), etc, are written.
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) {......} ...... }
program called PrintAnimalPattern , which uses println() 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.)
loops in a class called PrintPatterns. The signatures of the methods are: public static void printPatternX(int size) // 'X' from 'A' to ..., size is a positive integer.
(a) (b) (c) (d) Hints: On the diagonal, row = col. On the opposite diagonal, row + col = size + 1. # # # # # # # # # # # # # # # # # # # # # # # # # # # #
(e) (f) (g) (h) (i)
(j) (k) # # # # # # # #
(l) 1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1 2 1 2 3 4 5 6 7 2 1 7 6 5 4 3 2 1 1 2 3 1 2 3 4 5 6 3 2 1 6 5 4 3 2 1 1 2 3 4 1 2 3 4 5 4 3 2 1 5 4 3 2 1 1 2 3 4 5 1 2 3 4 5 4 3 2 1 4 3 2 1 1 2 3 4 5 6 1 2 3 6 5 4 3 2 1 3 2 1 1 2 3 4 5 6 7 1 2 7 6 5 4 3 2 1 2 1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1
(q) (r) 1 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 2 2 1 1 2 3 4 5 6 7 7 6 5 4 3 2 1 1 2 3 3 2 1 1 2 3 4 5 6 6 5 4 3 2 1 1 2 3 4 4 3 2 1 1 2 3 4 5 5 4 3 2 1 1 2 3 4 5 5 4 3 2 1 1 2 3 4 4 3 2 1 1 2 3 4 5 6 6 5 4 3 2 1 1 2 3 3 2 1 1 2 3 4 5 6 7 7 6 5 4 3 2 1 1 2 2 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 1 (s) (t) 1 2 3 2 3 4 5 4 3 4 5 6 7 6 5 4 5 6 7 8 9 8 7 6 5 6 7 8 9 0 1 0 9 8 7 6 7 8 9 0 1 2 3 2 1 0 9 8 7 8 9 0 1 2 3 4 5 4 3 2 1 0 9 8 (u)
loops in a class called PrintTriangles. The signatures of the methods are: public static void printXxxTriangle(int numRows) // Xxx is the pattern's name 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 1 1 1 2 1 1 2 1 1 3 3 1 1 3 3 1 1 4 6 4 1 1 4 6 4 1 1 5 10 10 5 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 6 15 20 15 6 1 (b) PascalTriangle1 (c) PascalTriangle
following series expansion, in a class called TrigonometricSeries. The headers of the methods are:
Compare the values computed using the series with the JDK methods Math.sin(), Math.cos() at x=0, π/6, π/4, π/3, π/2 using various numbers of terms. Hints: Avoid generating large numerator and denominator (which may cause arithmetic overflow, e.g., 13! is out of int range). Compute the terms as:
SpecialSeries. The signature of the method is:
Fibonacci numbers, which can be expressed as an int (i.e., 32-bit signed integer in the range of [- 2147483648, 2147483647]). The output shall look like: Hints: The maximum and minimum values of a 32-bit int are kept in constants Integer.MAX_VALUE and Integer.MIN_VALUE, respectively. Try these statements: 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 use F(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.
of n, for 1≤n≤10. Your output shall look like: The factorial of 1 is 1 The factorial of 2 is 2 ... public static double sumOfSeries(double x, int numTerms) F(0) = 1 F(1) = 1 F(2) = 2 ... F(45) = 1836311903 F(46) is out of the range of int System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); System.out.println(Integer.MAX_VALUE + 1); public static double sin(double x, int numTerms) // x in radians public static double cos(double x, int numTerms)