Create A Quiz Program In Java


  1. Often times, computer programs are used as a study method by educators. In this program, many of the concepts we have gone over thus far are put together to make a working quiz that asks math questions, and returns results on how the user did. For this program, the user is asked how many math questions they would like.
  2. Make a text file of questions into a quiz using Java FileReader I have an assignment to create an interactive quiz using a text file. A question is formatted like this (it's actually single spaced I had to separate the lines to keep the forum from smushing the whole thing together.).

The new file 'MultipleChoiceQuestion.java' should appear in the editor pane. Make sure it is also listed under '(default package)' in the 'Package Explorer' pane, along with 'Quiz.java'. Having both files in the same package eliminates complications with package imports and access specifiers when the 'Quiz' class tries to use the. Total hands-on programming experience. All core Java object-oriented concepts covered. Every concept explained with the help of a program. Mini-project at the end which covers a lot of object oriented concepts. Requires 2-3 hours of your time. I believe you will enjoy this course and make the most of it. In this clip, you'll learn how to create a simple calculator program with Java. Whether you're new to the Java object-oriented programming language or are a seasoned developer merely looking to improve your chops, you're sure to find benefit in this free video programming lesson. For more information, including detailed, step-by-step instructions, take a look. 2 Set the title of the program window (Quiz Program). 3 Let the program window close when the user clicks the close button. 4 Specify the width and height of the program window when it opens. 5 Specify the location of the program window when it opens. 6 Disable program window resizing. 7 Create a container object to act as the controls placeholder. Java If Else Quiz contains 10 single and multiple choice questions. If else quiz questions are designed in such a way that it will help you understand how if else statement works in Java. At the end of the quiz, result will be displayed along with your score and if else quiz answers.


Similar Messages:
ADVERTISEMENT

Trying To Create A Program That Provides Average Test Scores

Apr 13, 2014

I keep getting an error that says variable can't be found, what am I missing?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.Scanner;
public class testscores extends JFrame
[code]...

Program Should Exit Repetition Loop And Compute And Display Average Of Valid Grades Entered

Oct 26, 2014

My homework assignment is: Using a do-while statement, write a Java program that continuously requests a grade to be entered. If the grade is less than 0 or greater than 100, your program should display an appropriate message informing the user that an invalid grade has been entered; a valid grade should be added to a total. When a grade of 999 is entered, the program should exit the repetition loop and compute and display the average of the valid grades entered. Run the program on your computer and verify the program using appropriate test data.
When I run it, I don't get the correct average. I know that i'm supposed to enter 999 to exit the loop and to display the average, but 999 is being added with the loop. I'm not sure how to make it not do that.
//stephanie
import java.util.Scanner;
public class gradeAverage
{
public static void main(String[] args)
[code]....

Test Score Average Program In Java

Create A Quiz Program In Javascript

Jun 16, 2014

I'm working on a homework assignment and I keep getting a compiler message this is the message
GradesAverage.java:44: error: variable totalgrade might not have been initialized
System.out.println('Over all you have ' + totalgrade);
^
1 error
The homework is this Write a program that has variables to hold three test scores. The program should ask the user to enter three test scores and then assign the values entered to the variables. The program should display the average of the test stores and the letter grade that is assigned for the test score average. Use the grading scheme in the following table:
Test Score Average Letter Grade
90-100 A
80-89 B
70-79 C
60-69 D
Below 60 F
This is my code
import javax.swing.JOptionPane; // Needed for JOptionPane class
import java.util.Scanner; // Needed for the scanner class
public class GradesAverage
{
public static void main (String[] args)
[code]....

Java Program Using Nested Loop To Compute / Display Average Of Test Results For Each Experiment

Apr 2, 2015

Four experiments are performed, each consisting of six tests. The number of test results for each experiment is entered by the user. Write a Java program using a nested loop to compute and display the average of the test results for each experiment.
You can run the program by entering the following test results:
Experiment 1 results:23.231.516.927.525.428.6
Experiment 2 results:34.845.227.936.833.439.4
Experiment 3 results:19.416.810.220.818.913.4
Experiment 4 results:36.939.549.245.142.750.6

Student Grades For Three Exams And Average In Arrays?

Nov 12, 2014

For my lab this week I have to print out four arrays. The arrays have to be 5 units long. The first three arrays are the student's exam grades for exam 1, 2 & 3 and the fourth array should be the average for each student's three tests. The program should ask the user to input the grades in and then the program should compute the average. For example the program should print this if these are the exam grades the user imputs:
Exam 1 Exam 2 Exam 3 Average
65 79 80 74.66
79 82 59 73.33
99 100 98 99
and so on.......
I thought I wrote the program perfectly and when I compile it there are no errors but when I run it, it only lets me input the numbers for the first three students and then prints out something so strange.
here is my program:
public class Lab9{
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
int i, sum;
double avg;
sum = 0;
int A[ ] = new int [5];
int B[ ] = new int [5];
int C[ ] = new int [5];
double avg1[ ] = new double[5];
[code]....

Averaging Grades Program Not Adding Grades

Aug 18, 2014

Write a Swing program that declares an empty array of grades with a maximum length of 50. Implement a JOptionPane input box within a while loop to allow the user to enter grades. When the user enters the sentinel value of -1, that will signal the end of the data input loop.
After the grades are entered, a content pane should display the grades sorted from lowest to highest. Write a loop that goes through the array looking for elements that are greater than zero (0). Keep a running count of those items, and also accumulate them into a grand total. Divide the grand total by the number of grades entered to find an average, and display the average at the end of the sorted list of grades. Use the DecimalFormat method to display the average to 2 decimal places.

Reading Lowest / Highest / Average Grades And Reporting Them From For Loops?

May 3, 2014

import java.util.*;
import java.text.*;
public class Quiz {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
int quests = 0;
String input =';
[code]....
I'm not getting any errors anymore.

Find Weighted Average Of Four Test Scores

Create A Quiz Program In Java Developer

Apr 17, 2015

Write a program in JAVA in response to the following prompt:
Design a GUI program to find the weighted average of four test scores. The four test scores and their respective weights are given in the following format:
testscore1 weight1
...
For example, the sample data is as follows:
75 0.20
95 0.35
85 0.15
65 0.30
The user is supposed to enter the data and press a Calculate button. The program must display the weighted average.
Here is what I have written:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class weightedaverage2 extends JFrame {
private JLabel Score1L,Score2L,Score3L,Score4L;
[Code] .....

Trying To Create Custom Resource Bundle Shows Error

Jan 15, 2014

I am using jdev12c. I tried to create the following class
package view;
import java.awt.Dimension;
import java.util.ListResourceBundle;
public class Resource extends ListResourceBundle {
protected Object[][] getContents() {
return new Object[][] = {
[Code] ....
The code is copied from java documentation ListResourceBundle (Java Platform SE 7 )
Looks like a documentation bug where '=' has to be removed

Prompts User To Enter 5 Test Scores And Their Names - Calculate And Display Average

Sep 24, 2014

Using Bluejay. Need code that prompts user to enter 5 test scores and their names. Calculate the average and display.
First initial and last name , 5 test scores, and average

Program Shows No Output In Eclipse In NetBeans

Oct 1, 2014

It has no errors in it, but when it runs, it just doesn't show any output at all. Here's my code.
Fuel Class:
public class FuelGauge {
// Setting the gallons and the total amount of gallons
private int gallons;
final static int TotalGallons=15;
public FuelGauge(){
gallons=0;
}
// Initiate the number of gallons
public FuelGauge(int gallons){
[Code] .....

Program Shows Error While Using Super Keyword

Jan 3, 2015

//constructor
class Base
{
Base(int a) {
System.out.println('in base'+a);;
}
}
class Cons extends Base
[Code] .....

JSP :: Eclipse Project Window Shows Error But Code Editor Shows No Error

May 22, 2014

For my jsp file, the code editor shows no error, but the projects window shows an error. I built my project again, cleaned the project, restart eclipse twice and summoned cthulhu. But my project still shows an error. How do I find the cause.
Eclipse project -
JSP file -
<%@ page language='java' contentType='text/html; charset=ISO-8859-1'
pageEncoding='ISO-8859-1'%>
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>
<%@ taglib prefix='mine' uri='DiceFunctions'%>
[Code] ....

Program That Shows A Square Frame Filled With 100 Buttons Label

Apr 13, 2014

Write a program that shows a square frame filled with 100 buttons labeled 1 to 100. Nothing needs to happen when you press any of the buttons. I keep getting errors i am a beginner.
import java.awt.Frame;
import javax.swing.JButton;
import javax.swing.JPanel;
class TestFrame extends Frame {
[Code] ...

When Remove Increment Operator Program Shows Invalid Statement

Feb 19, 2015

class Brain56
{
public static int[] get()
{
return null;
}
public static void main(String...a)
{
int k=1;
get()[k]++;
}
}
when i remove the increment operator(get()[k]) program shows invalid statement may i know the reason behind it?

Take Grades Program And Make A Class

Jul 17, 2014

where to create the array of chars that hold the letter grade. I am assuming that would be in the main with the other arrays. Passing it into an object creating a method in the record.java. Then displaying it in my main.
Take the Grades program and make a class. An object that hold 5 student names, an array of 5 chars that hold the letter grades, 5 arrays of four doubles each to hold the set of test scores. The class should have methods that return a specific student's name, average test score and a letter grade based on the average. Demonstrate the class in a program that allows the user to enter each student's name and their 4 tests scores. It should then display each student's average and letter grade.This is my main program:
import java.util.Scanner;
public class GradeBook{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Record[] students = {new Record(), new Record(), new Record(), new Record(), new Record()};
for(int j=0; j < 5; j++){
[code]....

Create A Large Test Array

Mar 2, 2015

In my programming class we need to create a large test array of Longs to iteratively sum/reverse the array and recursively sum/reverse the array.creating the array and where to go from there.

Java Program That Converts Number Grades To Letter?

Aug 3, 2014

I wrote a java application that coverts number grades to letter grades. Here is what it looks like:
/java application to That corresponds the letter grade with the number grade
import java.util.Scanner; //program uses the class scanner
public class gradescore{
[Code]....

Write A Program Which Prompts User To Enter 4 Grades Between 0 And 100

Sep 2, 2014

I'm using Jgrasp and my prompt is asking me to write a program where the program prompts the user to enter 4 grades between 0 and 100. And you have to display the grades, and the program has to calculate the minimum grade, the maximum grade and the average.I'm just having problems with the max?
// Import Java Scanner.
import java.util.Scanner;
// Name Class.
public class Practice_4_1
[code]...

Program That Allows User To Enter Up To 10 Integer Grades Into Array

Apr 30, 2015

package question.pkg3;
import java.util.Scanner;
public class Question3 {
public static void main(String[] args) {
// TODO code application logic here
Scanner Luka=new Scanner(System.in);
double sum=0;double count=0;
int[] a=new int[10];
[code]....
I'm required to write a program that allows the user to enter up to 10 integer grades into an array. Stop the loop by typing in ‐1. Your main method should call an Average method that returns the average of the grades.I There's something wrong with my program , the count always stays 0 and the sum is always 1 less than the actual sum.Sample input and output :
Enter grade 1: 8
Enter grade 2: 9
Enter grade 3: 10
Enter grade 4: 5
Enter grade 5: 8
Enter grade 6: 9
Enter grade 7: -1
output
Average grade is 8.1666666667On line 13 I had count=count+1 ;

Create Two Instances Of Class And Test Each Of Methods

Nov 1, 2014

How do I use two constructors and I'm having trouble with using char for gender...
Write a program to test the Person class defined below. Your test program should create two instances of the class (each to test a different constructor) and test each of the methods. You are also required to illustrate the error in trying to access private data members from the client class (for clarity temporarily change the private modifier to public and test again). See screenshots below for sample output.
The screen shots are displayed as:
p1 name = Not Given Age = 0 Gender = U
p2 name = Jane Doe Age = 0 Gender = F
p1 name = John Doe Age = 25 Gender = M
and
PersonTester.jave:20: name has private access in Person
System.out.println('p2 name = ' + p2.name + 'Age = ' + p2.age + 'Gender = ' + p2.gender);
PersonTester.jave:20: age has private access in Person
System.out.println('p2 name = ' + p2.name + 'Age = ' + p2.age + 'Gender = ' + p2.gender);
PersonTester.jave:20: gender has private access in Person
System.out.println('p2 name = ' + p2.name + 'Age = ' + p2.age + 'Gender = ' + p2.gender);
3 errors
Here is the class given :
class Person {
// Data Members
private String name; // The name of this person
private int age; // The age of this person
private char gender; // The gender of this person
[Code] .....

Averaging Grades Program Throwing Exception With Negative Numbers

Nov 17, 2014

So I have re-written the code but it is still not running correctly. Any number i type in it throws an exception, also i need the program to add the totals that i type in and then once i type -1 into the prompt button list all the number i typed in and give me the average.
import java.awt.*;
import java.awt.event.*;
import javax.swing .*;
import javax.swing.text.*;
public class Averages extends JFrame
{
//construct components
JLabel sortPrompt = new JLabel('Sort By:');
[Code] .....

Averaging Grades Program - System Crashes On Negative Number Input

Sep 30, 2014

I do now have the problem where i have to insert the numbers 1 to 100 individually in order to allow the program to accept a grade as high as 100%.
Also as soon as i type in a negative number the system crashes and shows me a error as attached.
/*
Averaging grades
To use the Java Swing interface to calculate the average of up to 50 grades.Average is calculated once -1 is entered as a value. The grades are then sorted from lowest to highest and displayed in a content pane which also displays the average.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing .*;
import javax.swing.text.*;
public class Averages extends JFrame {
//construct components
JLabel sortPrompt = new JLabel('Sort By:');
[Code] ....

Averaging Grades Program - Take Input From User Until They Enter Negative Number

Feb 2, 2015

Ok so I have my program working for the most part. In this program I am supposed to take input from the user until they enter a negative number and that works, the problem is that it doesn't work if I enter a negative number on the first prompt. For example if I enter a 100 it would prompt me again and if I enter a negative number it would quit and give me the average, but if I enter a negative number the first time I am prompted the program just gives me an error. How do I fix that?
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
public class Application {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
List<Integer> grades;
[Code] ....

GPA And Average Program

Mar 25, 2014

I am new on this and I will be working in a gpa and average program. This is my code so far: Every time that I try to add the gpa part it gives me errors or just duplicates whatever I've in average and displays it in gpa
/**
* This program shows a database of students in a school.
* It gathers information as name, classes, grades, and calculates average and gpa average.
*
*/
import javax.swing.JOptionPane;
[code]....

Exercises on Classes

Ex: The Circle Class (An Introduction to Classes and Instances)

This first exercise shall lead you through all the basic concepts in OOP.

A class called circle is designed as shown in the following class diagram. It contains:

  • Two private instance variables: radius (of the type double) and color (of the type String), with default value of 1.0 and 'red', respectively.
  • Two overloaded constructors - a default constructor with no argument, and a constructor which takes a double argument for radius.
  • Two public methods: getRadius() and getArea(), which return the radius and area of this instance, respectively.

The source codes for Circle.java is as follows:

Compile 'Circle.java'. Can you run the Circle class? Why?

This Circle class does not have a main() method. Hence, it cannot be run directly. This Circle class is a “building block” and is meant to be used in another program.

Let us write a test program called TestCircle (in another source file called TestCircle.java) which uses the Circle class, as follows:

Now, run the TestCircle and study the results.

More Basic OOP Concepts
  1. Constructor: Modify the class Circle to include a third constructor for constructing a Circle instance with two arguments - a double for radius and a String for color. Modify the test program TestCircle to construct an instance of Circle using this constructor.
  2. Getter: Add a getter for variable color for retrieving the color of this instance. Modify the test program to test this method.
  3. public vs. private: In TestCircle, can you access the instance variable radius directly (e.g., System.out.println(c1.radius)); or assign a new value to radius (e.g., c1.radius=5.0)? Try it out and explain the error messages.
  4. Setter: Is there a need to change the values of radius and color of a Circle instance after it is constructed? If so, add two public methods called setters for changing the radius and color of a Circle instance as follows: Modify the TestCircle to test these methods, e.g.,
  5. Keyword 'this': Instead of using variable names such as r (for radius) and c (for color) in the methods' arguments, it is better to use variable names radius (for radius) and color (for color) and use the special keyword 'this' to resolve the conflict between instance variables and methods' arguments. For example, Modify ALL the constructors and setters in the Circle class to use the keyword 'this'.
  6. Method toString(): Every well-designed Java class should contain a public method called toString() that returns a description of the instance (in the return type of String). The toString() method can be called explicitly (via instanceName.toString()) just like any other method; or implicitly through println(). If an instance is passed to the println(anInstance) method, the toString() method of that instance will be invoked implicitly. For example, include the following toString() methods to the Circle class: Try calling toString() method explicitly, just like any other method: toString() is called implicitly when an instance is passed to println() method, for example,

The final class diagram for the Circle class is as follows:

Ex: Yet Another Circle Class

Ex: The Rectangle Class

Ex: The Employee Class

Ex: The InvoiceItem Class

Ex: The Account Class

Ex: The Date Class

Ex: The Time Class

Ex: The Ball Class

Exercises on Composition

Ex: The Author and Book Classes (An Introduction to OOP Composition)

This first exercise shall lead you through all the concepts involved in OOP Composition.

A class called Author (as shown in the class diagram) is designed to model a book's author. It contains:

  • Three private instance variables: name (String), email (String), and gender (char of either 'm' or 'f');
  • One constructor to initialize the name, email and gender with the given values; (There is no default constructor for Author, as there are no defaults for name, email and gender.)
  • public getters/setters: getName(), getEmail(), setEmail(), and getGender();
    (There are no setters for name and gender, as these attributes cannot be changed.)
  • A toString() method that returns 'Author[name=?,email=?,gender=?]', e.g., 'Author[name=Tan Ah Teck,email=ahTeck@somewhere.com,gender=m]'.

Write the Author class. Also write a test driver called TestAuthor to test all the public methods, e.g.,


A class called Book is designed (as shown in the class diagram) to model a book written by one author. It contains:

  • Four private instance variables: name (String), author (of the class Author you have just created, assume that a book has one and only one author), price (double), and qty (int);
  • Two constructors:
  • public methods getName(), getAuthor(), getPrice(), setPrice(), getQty(), setQty().
  • A toString() that returns 'Book[name=?,Author[name=?,email=?,gender=?],price=?,qty=?'. You should reuse Author’s toString().

Write the Book class (which uses the Author class written earlier). Also write a test driver called TestBook to test all the public methods in the class Book. Take Note that you have to construct an instance of Author before you can construct an instance of Book. E.g.,

Take note that both Book and Author classes have a variable called name. However, it can be differentiated via the referencing instance. For a Book instance says aBook, aBook.name refers to the name of the book; whereas for an Author's instance say auAuthor, anAuthor.name refers to the name of the author. There is no need (and not recommended) to call the variables bookName and authorName.

TRY:

  1. Printing the name and email of the author from a Book instance. (Hint: aBook.getAuthor().getName(), aBook.getAuthor().getEmail()).
  2. Introduce new methods called getAuthorName(), getAuthorEmail(), getAuthorGender() in the Book class to return the name, email and gender of the author of the book. For example,

Ex (Advanced): Book and Author Classes Again - An Array of Objects as an Instance Variable

In the earlier exercise, a book is written by one and only one author. In reality, a book can be written by one or more author. Modify the Book class to support one or more authors by changing the instance variable authors to an Author array.

Notes:

  • The constructors take an array of Author (i.e., Author[]), instead of an Author instance. In this design, once a Book instance is constructor, you cannot add or remove author.
  • The toString() method shall return 'Book[name=?,authors={Author[name=?,email=?,gender=?],......},price=?,qty=?]'.

You are required to:

  1. Write the code for the Book class. You shall re-use the Author class written earlier.
  2. Write a test driver (called TestBook) to test the Book class.

Hints:

Ex: The MyPoint Class

A class called MyPoint, which models a 2D point with x and y coordinates, is designed as shown in the class diagram. It contains:

  • Two instance variables x (int) and y (int).
  • A default (or 'no-argument' or 'no-arg') constructor that construct a point at the default location of (0, 0).
  • A overloaded constructor that constructs a point with the given x and y coordinates.
  • Getter and setter for the instance variables x and y.
  • A method setXY() to set both x and y.
  • A method getXY() which returns the x and y in a 2-element int array.
  • A toString() method that returns a string description of the instance in the format '(x, y)'.
  • A method called distance(int x, int y) that returns the distance from this point to another point at the given (x, y) coordinates, e.g.,
  • An overloaded distance(MyPoint another) that returns the distance from this point to the given MyPoint instance (called another), e.g.,
  • Another overloaded distance() method that returns the distance from this point to the origin (0,0), e.g.,

You are required to:

  1. Write the code for the class MyPoint. Also write a test program (called TestMyPoint) to test all the methods defined in the class.
    Hints:
  2. Write a program that allocates 10 points in an array of MyPoint, and initializes to (1, 1), (2, 2), ... (10, 10).
    Hints: You need to allocate the array, as well as each of the 10 MyPoint instances. In other words, you need to issue 11 new, 1 for the array and 10 for the MyPoint instances.

Notes: Point is such a common entity that JDK certainly provided for in all flavors.

Ex: The MyCircle and MyPoint Classes

A class called MyCircle, which models a circle with a center(x,y) and a radius, is designed as shown in the class diagram. The MyCircle class uses an instance of MyPoint class (created in the previous exercise) as its center.

The class contains:

  • Two private instance variables: center (an instance of MyPoint) and radius (int).
  • A constructor that constructs a circle with the given center's (x, y) and radius.
  • An overloaded constructor that constructs a MyCircle given a MyPoint instance as center, and radius.
  • A default constructor that construct a circle with center at (0,0) and radius of 1.
  • Various getters and setters.
  • A toString() method that returns a string description of this instance in the format 'MyCircle[radius=r,center=(x,y)]'. You shall reuse the toString() of MyPoint.
  • getArea() and getCircumference() methods that return the area and circumference of this circle in double.
  • A distance(MyCircle another) method that returns the distance of the centers from this instance and the given MyCircle instance. You should use MyPoint’s distance() method to compute this distance.

Write the MyCircle class. Also write a test driver (called TestMyCircle) to test all the public methods defined in the class.

Hints:

Ex: The MyTriangle and MyPoint Classes

A class called MyTriangle, which models a triangle with 3 vertices, is designed as shown. The MyTriangle class uses three MyPoint instances (created in the earlier exercise) as its three vertices.

It contains:

  • Three private instance variables v1, v2, v3 (instances of MyPoint), for the three vertices.
  • A constructor that constructs a MyTriangle with three set of coordinates, v1=(x1, y1), v2=(x2, y2), v3=(x3, y3).
  • An overloaded constructor that constructs a MyTriangle given three instances of MyPoint.
  • A toString() method that returns a string description of the instance in the format 'MyTriangle[v1=(x1,y1),v2=(x2,y2),v3=(x3,y3)]'.
  • A getPerimeter() method that returns the length of the perimeter in double. You should use the distance() method of MyPoint to compute the perimeter.
  • A method printType(), which prints 'equilateral' if all the three sides are equal, 'isosceles' if any two of the three sides are equal, or 'scalene' if the three sides are different.

Write the MyTriangle class. Also write a test driver (called TestMyTriangle) to test all the public methods defined in the class.

Ex: The MyRectangle and MyPoint Classes

Design a MyRectangle class which is composed of two MyPoint instances as its top-left and bottom-right corners. Draw the class diagrams, write the codes, and write the test drivers.

Ex: The Customer and Invoice classes

The Customer class models a customer is design as shown in the class diagram. Write the codes for the Customer class and a test driver to test all the public methods.

The Invoice class, design as shown in the class diagram, composes a Customer instance (written earlier) as its member. Write the codes for the Invoice class and a test driver to test all the public methods.

Ex: The Customer and Account classes

The Customer class models a customer is design as shown in the class diagram. Write the codes for the Customer class and a test driver to test all the public methods.

The Account class models a bank account, design as shown in the class diagram, composes a Customer instance (written earlier) as its member. Write the codes for the Account class and a test driver to test all the public methods.

More Exercises on Classes

Ex: The MyComplex class

A class called MyComplex, which models complex numbers x+yi, is designed as shown in the class diagram. It contains:

  • Two instance variable named real (double) and imag (double) which stores the real and imaginary parts of the complex number, respectively.
  • A constructor that creates a MyComplex instance with the given real and imaginary values.
  • A default constructor that create a MyComplex at 0.0 + 0.0i.
  • Getters and setters for instance variables real and imag.
  • A method setValue() to set the value of the complex number.
  • A toString() that returns '(x + yi)' where x and y are the real and imaginary parts, respectively.
  • Methods isReal() and isImaginary() that returns true if this complex number is real or imaginary, respectively.
    Hints:
  • A method equals(double real, double imag) that returns true if this complex number is equal to the given complex number (real, imag).
    Hints:
  • An overloaded equals(MyComplex another) that returns true if this complex number is equal to the given MyComplex instance another.
    Hints:
  • A method magnitude() that returns the magnitude of this complex number.
  • Methods argument() that returns the argument of this complex number in radians (double). Note: The Math library has two arc-tangent methods, Math.atan(double) and Math.atan2(double, double). We commonly use the Math.atan2(y, x) instead of Math.atan(y/x) to avoid division by zero. Read the documentation of Math class in package java.lang.
  • Methods add(MyComplex right) and subtract(MyComplex right) that adds and subtract the given MyComplex instance (called right), into/from this instance and returns this instance. Hints:
  • Methods addNew(MyComplex right) and subtractNew(MyComplex right) that adds and subtract this instance with the given MyComplex instance called right, and returns a new MyComplex instance containing the result.
    Hint:
  • Methods multiply(MyComplex right) and divide(MyComplex right) that multiplies and divides this instance with the given MyComplex instance right, and keeps the result in this instance, and returns this instance.
  • A method conjugate() that operates on this instance and returns this instance containing the complex conjugate.

You are required to:

  1. Write the MyComplex class.
  2. Write a test driver to test all the public methods defined in the class.
  3. Write an application called MyComplexApp that uses the MyComplex class. The application shall prompt the user for two complex numbers, print their values, check for real, imaginary and equality, and carry out all the arithmetic operations.

Take note that there are a few flaws in the design of this class, which was introduced solely for teaching purpose:

  • Comparing doubles in equal() using ' may produce unexpected outcome. For example, (2.2+4.4)6.6 returns false. It is common to define a small threshold called EPSILON (set to about 10^-8) for comparing floating point numbers.
  • The method addNew(), subtractNew() produce new instances, whereas add(), subtract(), multiply(), divide() and conjugate() modify this instance. There is inconsistency in the design (introduced for teaching purpose).

Also take note that methods such as add() returns an instance of MyComplex. Hence, you can place the result inside a System.out.println() (which implicitly invoke the toString()). You can also chain the operations, e.g., c1.add(c2).add(c3) (same as (c1.add(c2)).add(c3)), or c1.add(c2).subtract(c3).

Ex: The MyPolynomial Class

A class called MyPolynomial, which models polynomials of degree-n (see equation), is designed as shown in the class diagram.

It contains:

  • An instance variable named coeffs, which stores the coefficients of the n-degree polynomial in a double array of size n+1, where c0 is kept at index 0.
  • A constructor MyPolynomial(coeffs:double...) that takes a variable number of doubles to initialize the coeffs array, where the first argument corresponds to c0.
    The three dots is known as varargs (variable number of arguments), which is a new feature introduced in JDK 1.5. It accepts an array or a sequence of comma-separated arguments. The compiler automatically packs the comma-separated arguments in an array. The three dots can only be used for the last argument of the method.
    Hints:
  • A method getDegree() that returns the degree of this polynomial.
  • A method toString() that returns 'cnx^n+cn-1x^(n-1)+...+c1x+c0'.
  • A method evaluate(double x) that evaluate the polynomial for the given x, by substituting the given x into the polynomial expression.
  • Methods add() and multiply() that adds and multiplies this polynomial with the given MyPolynomial instance another, and returns this instance that contains the result.

Write the MyPolynomial class. Also write a test driver (called TestMyPolynomial) to test all the public methods defined in the class.

Question: Do you need to keep the degree of the polynomial as an instance variable in the MyPolynomial class in Java? How about C/C++? Why?

Ex: Using JDK's BigInteger Class

Recall that primitive integer type byte, short, int and long represent 8-, 16-, 32-, and 64-bit signed integers, respectively. You cannot use them for integers bigger than 64 bits. Java API provides a class called BigInteger in a package called java.math. Study the API of the BigInteger class (Java API ⇒ From 'Packages', choose 'java.math' ' From 'classes', choose 'BigInteger' ' Study the constructors (choose 'CONSTR') on how to construct a BigInteger instance, and the public methods available (choose 'METHOD'). Look for methods for adding and multiplying two BigIntegers.

Write a program called TestBigInteger that:

  1. adds '11111111111111111111111111111111111111111111111111111111111111' to '22222222222222222222222222222222222222222222222222' and prints the result.
  2. multiplies the above two number and prints the result.

Hints:

Ex: The MyTime Class

A class called MyTime, which models a time instance, is designed as shown in the class diagram.

It contains the following private instance variables:

  • hour: between 0 to 23.
  • minute: between 0 to 59.
  • Second: between 0 to 59.

You are required to perform input validation.

It contains the following public methods:

  • setTime(int hour, int minute, int second): It shall check if the given hour, minute and second are valid before setting the instance variables.
    (Advanced: Otherwise, it shall throw an IllegalArgumentException with the message 'Invalid hour, minute, or second!'.)
  • Setters setHour(int hour), setMinute(int minute), setSecond(int second): It shall check if the parameters are valid, similar to the above.
  • Getters getHour(), getMinute(), getSecond().
  • toString(): returns 'HH:MM:SS'.
  • nextSecond(): Update this instance to the next second and return this instance. Take note that the nextSecond() of 23:59:59 is 00:00:00.
  • nextMinute(), nextHour(), previousSecond(), previousMinute(), previousHour(): similar to the above.

Write the code for the MyTime class. Also write a test driver (called TestMyTime) to test all the public methods defined in the MyTime class.

Ex: The MyDate Class

A class called MyDate, which models a date instance, is defined as shown in the class diagram.

The MyDate class contains the following private instance variables:

  • year (int): Between 1 to 9999.
  • month (int): Between 1 (Jan) to 12 (Dec).
  • day (int): Between 1 to 28|29|30|31, where the last day depends on the month and whether it is a leap year for Feb (28|29).

It also contains the following publicstatic final variables (drawn with underlined in the class diagram):

  • MONTHS (String[]), DAYS (String[]), and DAY_IN_MONTHS (int[]): static variables, initialized as shown, which are used in the methods.

The MyDate class has the following publicstatic methods (drawn with underlined in the class diagram):

  • isLeapYear(int year): returns true if the given year is a leap year. A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
  • isValidDate(int year, int month, int day): returns true if the given year, month, and day constitute a valid date. Assume that year is between 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 on Feb.
  • 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. Read the earlier exercise on how to determine the day of the week (or Wiki 'Determination of the day of the week').

The MyDate class has one constructor, which takes 3 parameters: year, month and day. It shall invoke setDate() method (to be described later) to set the instance variables.

The MyDate class has the following public methods:

Create A Quiz Program In Java Programming

  • setDate(int year, int month, int day): It shall invoke the static method isValidDate() to verify that the given year, month and day constitute a valid date.
    (Advanced: Otherwise, it shall throw an IllegalArgumentException with the message 'Invalid year, month, or day!'.)
  • setYear(int year): It shall verify that the given year is between 1 and 9999.
    (Advanced: Otherwise, it shall throw an IllegalArgumentException with the message 'Invalid year!'.)
  • setMonth(int month): It shall verify that the given month is between 1 and 12.
    (Advanced: Otherwise, it shall throw an IllegalArgumentException with the message 'Invalid month!'.)
  • setDay(int day): It shall verify that the given day is between 1 and dayMax, where dayMax depends on the month and whether it is a leap year for Feb.
    (Advanced: Otherwise, it shall throw an IllegalArgumentException with the message 'Invalid month!'.)
  • getYear(), getMonth(), getDay(): return the value for the year, month and day, respectively.
  • toString(): returns a date string in the format 'xxxday d mmm yyyy', e.g., 'Tuesday 14 Feb 2012'.
  • nextDay(): update this instance to the next day and return this instance. Take note that nextDay() for 31 Dec 2000 shall be 1 Jan 2001.
  • nextMonth(): update this instance to the next month and return this instance. Take note that nextMonth() for 31 Oct 2012 shall be 30 Nov 2012.
  • nextYear(): update this instance to the next year and return this instance. Take note that nextYear() for 29 Feb 2012 shall be 28 Feb 2013.
    (Advanced: throw an IllegalStateException with the message 'Year out of range!' if year > 9999.)
  • previousDay(), previousMonth(), previousYear(): similar to the above.

Write the code for the MyDate class.

Use the following test statements to test the MyDate class:

Write a test program that tests the nextDay() in a loop, by printing the dates from 28 Dec 2011 to 2 Mar 2012.

Ex: Bouncing Balls - Ball and Container Classes

A class called Ball is designed as shown in the class diagram.

The Ball class contains the following private instance variables:

  • x, y and radius, which represent the ball's center (x, y) co-ordinates and the radius, respectively.
  • xDelta (Δx) and yDelta (Δy), which represent the displacement (movement) per step, in the x and y direction respectively.

The Ball class contains the following public methods:

  • A constructor which accepts x, y, radius, speed, and direction as arguments. For user friendliness, user specifies speed (in pixels per step) and direction (in degrees in the range of (-180°, 180°]). For the internal operations, the speed and direction are to be converted to (Δx, Δy) in the internal representation. Note that the y-axis of the Java graphics coordinate system is inverted, i.e., the origin (0, 0) is located at the top-left corner.
  • Getter and setter for all the instance variables.
  • A method move() which move the ball by one step.
  • reflectHorizontal() which reflects the ball horizontally (i.e., hitting a vertical wall)
  • reflectVertical() (the ball hits a horizontal wall).
  • toString() which prints the message 'Ball at (x, y) of velocity (Δx, Δy)'.

Write the Ball class. Also write a test program to test all the methods defined in the class.


A class called Container, which represents the enclosing box for the ball, is designed as shown in the class diagram. It contains:

  • Instance variables (x1, y1) and (x2, y2) which denote the top-left and bottom-right corners of the rectangular box.
  • A constructor which accepts (x, y) of the top-left corner, width and height as argument, and converts them into the internal representation (i.e., x2=x1+width-1). Width and height is used in the argument for safer operation (there is no need to check the validity of x2>x1 etc.).
  • A toString() method that returns 'Container at (x1,y1) to (x2, y2)'.
  • A boolean method called collidesWith(Ball), which check if the given Ball is outside the bounds of the container box. If so, it invokes the Ball's reflectHorizontal() and/or reflectVertical() to change the movement direction of the ball, and returns true.

Use the following statements to test your program:

Ex: The Ball and Player Classes

The Ball class, which models the ball in a soccer game, is designed as shown in the class diagram. Write the codes for the Ball class and a test driver to test all the public methods.

The Player class, which models the players in a soccer game, is designed as shown in the class diagram. The Player interacts with the Ball (written earlier). Write the codes for the Player class and a test driver to test all the public methods. Make your assumption for the kick().

Can you write a very simple soccer game with 2 teams of players and a ball, inside a soccer field?

Exercises on Inheritance

Ex: The Circle and Cylinder Classes

This exercise shall guide you through the important concepts in inheritance.

In this exercise, a subclass called Cylinder is derived from the superclass Circle as shown in the class diagram (where an an arrow pointing up from the subclass to its superclass). Study how the subclass Cylinder invokes the superclass' constructors (via super() and super(radius)) and inherits the variables and methods from the superclass Circle.

You can reuse the Circle class that you have created in the previous exercise. Make sure that you keep 'Circle.class' in the same directory.

Write a test program (says TestCylinder) to test the Cylinder class created, as follow:

Method Overriding and 'Super': The subclass Cylinder inherits getArea() method from its superclass Circle. Try overriding the getArea() method in the subclass Cylinder to compute the surface area (=2π×radius×height + 2×base-area) of the cylinder instead of base area. That is, if getArea() is called by a Circle instance, it returns the area. If getArea() is called by a Cylinder instance, it returns the surface area of the cylinder.

If you override the getArea() in the subclass Cylinder, the getVolume() no longer works. This is because the getVolume() uses the overriddengetArea() method found in the same class. (Java runtime will search the superclass only if it cannot locate the method in this class). Fix the getVolume().

Hints: After overridding the getArea() in subclass Cylinder, you can choose to invoke the getArea() of the superclass Circle by calling super.getArea().

TRY:

Provide a toString() method to the Cylinder class, which overrides the toString() inherited from the superclass Circle, e.g.,

Try out the toString() method in TestCylinder.

Note: @Override is known as annotation (introduced in JDK 1.5), which asks compiler to check whether there is such a method in the superclass to be overridden. This helps greatly if you misspell the name of the toString(). If @Override is not used and toString() is misspelled as ToString(), it will be treated as a new method in the subclass, instead of overriding the superclass. If @Override is used, the compiler will signal an error. @Override annotation is optional, but certainly nice to have.

Ex: Superclass Person and its subclasses

Ex: Point2D and Point3D

Ex: Point and MovablePoint

Ex: Superclass Shape and its subclasses Circle, Rectangle and Square

Write a superclass called Shape (as shown in the class diagram), which contains:

  • Two instance variables color (String) and filled (boolean).
  • Two constructors: a no-arg (no-argument) constructor that initializes the color to 'green' and filled to true, and a constructor that initializes the color and filled to the given values.
  • Getter and setter for all the instance variables. By convention, the getter for a boolean variable xxx is called isXXX() (instead of getXxx() for all the other types).
  • A toString() method that returns 'A Shape with color of xxx and filled/Not filled'.

Write a test program to test all the methods defined in Shape.

Write two subclasses of Shape called Circle and Rectangle, as shown in the class diagram.

The Circle class contains:

  • An instance variable radius (double).
  • Three constructors as shown. The no-arg constructor initializes the radius to 1.0.
  • Getter and setter for the instance variable radius.
  • Methods getArea() and getPerimeter().
  • Override the toString() method inherited, to return 'A Circle with radius=xxx, which is a subclass of yyy', where yyy is the output of the toString() method from the superclass.

The Rectangle class contains:

  • Two instance variables width (double) and length (double).
  • Three constructors as shown. The no-arg constructor initializes the width and length to 1.0.
  • Getter and setter for all the instance variables.
  • Methods getArea() and getPerimeter().
  • Override the toString() method inherited, to return 'A Rectangle with width=xxx and length=zzz, which is a subclass of yyy', where yyy is the output of the toString() method from the superclass.

Write a class called Square, as a subclass of Rectangle. Convince yourself that Square can be modeled as a subclass of Rectangle. Square has no instance variable, but inherits the instance variables width and length from its superclass Rectangle.

  • Provide the appropriate constructors (as shown in the class diagram). Hint:
  • Override the toString() method to return 'A Square with side=xxx, which is a subclass of yyy', where yyy is the output of the toString() method from the superclass.
  • Do you need to override the getArea() and getPerimeter()? Try them out.
  • Override the setLength() and setWidth() to change both the width and length, so as to maintain the square geometry.

Exercises on Composition vs Inheritance

They are two ways to reuse a class in your applications: composition and inheritance.

Ex: The Point and Line Classes

Let us begin with composition with the statement 'a line composes of two points'.

Complete the definition of the following two classes: Point and Line. The class Line composes 2 instances of class Point, representing the beginning and ending points of the line. Also write test classes for Point and Line (says TestPoint and TestLine).

The class diagram for composition is as follows (where a diamond-hollow-head arrow pointing to its constituents):

Instead of composition, we can design a Line class using inheritance. Instead of 'a line composes of two points', we can say that 'a line is a point extended by another point', as shown in the following class diagram:

Let's re-design the Line class (called LineSub) as a subclass of class Point. LineSub inherits the starting point from its superclass Point, and adds an ending point. Complete the class definition. Write a testing class called TestLineSub to test LineSub.

Summary: There are two approaches that you can design a line, composition or inheritance. 'A line composes two points' or 'A line is a point extended with another point'”. Compare the Line and LineSub designs: Line uses composition and LineSub uses inheritance. Which design is better?

Ex: The Circle and Cylinder Classes Using Composition

Try rewriting the Circle-Cylinder of the previous exercise using composition (as shown in the class diagram) instead of inheritance. That is, 'a cylinder is composed of a base circle and a height'.

Which design (inheritance or composition) is better?

Exercises on Polymorphism, Abstract Classes and Interfaces

Ex: Abstract Superclass Shape and Its Concrete Subclasses

Rewrite the superclass Shape and its subclasses Circle, Rectangle and Square, as shown in the class diagram.

In this exercise, Shape shall be defined as an abstract class, which contains:

  • Two protected instance variables color(String) and filled(boolean). The protected variables can be accessed by its subclasses and classes in the same package. They are denoted with a '#' sign in the class diagram.
  • Getter and setter for all the instance variables, and toString().
  • Two abstract methods getArea() and getPerimeter() (shown in italics in the class diagram).

The subclasses Circle and Rectangle shall override the abstract methods getArea() and getPerimeter() and provide the proper implementation. They also override the toString().

Write a test class to test these statements involving polymorphism and explain the outputs. Some statements may trigger compilation errors. Explain the errors, if any.

What is the usage of the abstract method and abstract class?

Ex: Polymorphism

Examine the following codes and draw the class diagram.

Explain the outputs (or error) for the following test program.

Ex: Interface Movable and its implementations MovablePoint and MovableCircle

Suppose that we have a set of objects with some common behaviors: they could move up, down, left or right. The exact behaviors (such as how to move and how far to move) depend on the objects themselves. One common way to model these common behaviors is to define an interface called Movable, with abstract methods moveUp(), moveDown(), moveLeft() and moveRight(). The classes that implement the Movable interface will provide actual implementation to these abstract methods.

Let's write two concrete classes - MovablePoint and MovableCircle - that implement the Movable interface.

The code for the interface Movable is straight forward.

For the MovablePoint class, declare the instance variable x, y, xSpeed and ySpeed with package access as shown with '~' in the class diagram (i.e., classes in the same package can access these variables directly). For the MovableCircle class, use a MovablePoint to represent its center (which contains four variable x, y, xSpeed and ySpeed). In other words, the MovableCircle composes a MovablePoint, and its radius.

Write a test program and try out these statements:

Make Quiz Program In Java

Write a new class called MovableRectangle, which composes two MovablePoints (representing the top-left and bottom-right corners) and implementing the Movable Interface. Make sure that the two points has the same speed.

What is the difference between an interface and an abstract class?

Ex: Interfaces GeometricObject and Resizable

  1. Write the interface called GeometricObject, which declares two abstract methods: getParameter() and getArea(), as specified in the class diagram.
    Hints:
  2. Write the implementation class Circle, with a protected variable radius, which implements the interface GeometricObject.
    Hints:
  3. Write a test program called TestCircle to test the methods defined in Circle.
  4. The class ResizableCircle is defined as a subclass of the class Circle, which also implements an interface called Resizable, as shown in class diagram. The interface Resizable declares an abstract method resize(), which modifies the dimension (such as radius) by the given percentage. Write the interface Resizable and the class ResizableCircle.
    Hints:
  5. Write a test program called TestResizableCircle to test the methods defined in ResizableCircle.

More Exercises on OOP

Ex: The Discount System

You are asked to write a discount system for a beauty saloon, which provides services and sells beauty products. It offers 3 types of memberships: Premium, Gold and Silver. Premium, gold and silver members receive a discount of 20%, 15%, and 10%, respectively, for all services provided. Customers without membership receive no discount. All members receives a flat 10% discount on products purchased (this might change in future). Your system shall consist of three classes: Customer, Discount and Visit, as shown in the class diagram. It shall compute the total bill if a customer purchases $x of products and $y of services, for a visit. Also write a test program to exercise all the classes.

The class DiscountRate contains only static variables and methods (underlined in the class diagram).

Create A Quiz Program In Java Compiler

Ex: Polyline of Points with ArrayList

A polyline is a line with segments formed by points. Let's use the ArrayList (dynamically allocated array) to keep the points, but upcast to List in the instance variable. (Take note that array is of fixed-length, and you need to set the initial length).

Program

Exercises on Data Structures

Ex: MyIntStack

A stack is a first-in-last-out queue. Write a program called MyIntStack, which uses an array to store the contents, restricted to int.

Write a test program.

Try:

  1. Modify the push() method to throw an IllegalStateException if the stack is full.
  2. Modify the push() to return true if the operation is successful, or false otherwise.
  3. Modify the push() to increase the capacity by reallocating another array, if the stack is full.

Exercise (Nodes, Link Lists, Trees, Graphs):

[TODO]

  • Study the existing open source codes, including JDK.
  • Specialized algorithms, such as shortest path.

Exercise (Maps):

[TODO]

  • Representation of map data.
  • Specialized algorithms, such as shortest path.

Exercise (Matrix Operations for 3D Graphics):

[TODO]

  • Study the existing open source codes, including JDK's 2D Graphics and JOGL's 3D Graphics.
  • Efficient and specialized codes for 3D Graphics (4D matrices). Handle various primitive types such as int, float and double efficiently.