Java 200 LManual
Java 200 LManual
___________________________________________________
Prepared by:
Eng. Aisha Alkandari
Eng. Aisha Alnoori
Eng. Basma Alfahad
Eng. Zainab Bahbahani
Supervised by:
Dr. Asmaa Alsumait
Table of contents
Step 1: Download
Download Eclipse from https://www.eclipse.org/downloads/packages/installer. The Eclipse
Installer 2022-03 R now includes a JRE for macOS, Windows and Linux.
If the "Welcome" screen shows up, close it by clicking the "close" button next to the "Welcome"
title.
3. The source file "Hello.java" opens on the editor panel (the center pane). Enter
the code below
3. The output "Hello, world!" appears on the Console pane (the bottom pane).
NOTES:
• You should create a NEW Java "project" for EACH of your Java application.
• Nonetheless, Eclipse allows you to keep more than one programs (classes) in a
project, which is handy for writing toy programs. To run a particular program, open
and right-click on the source file ⇒ Run As ⇒ Java Application.
• Clicking the "Run" button (with a "Play" icon) runs the recently-run program (based
on the previous configuration). Try clicking on the "down-arrow" besides the "Run"
button.
Eclipse performs incremented compilation, as and when a source "line" is entered. It marked
a source line having syntax error with a RED CROSS. Place your cursor at the RED CROSS
to view the error message.
You CANNOT RUN the program if there is any syntax error (marked by a RED CROSS
before the filename).
Correct all the syntax errors and RUN the program.
HINTS:
In some cases, Eclipse shows an ORANGE LIGHT-BULB (for HINTS) next to the ERROR
RED-CROSS (Line 5 in the above diagram). You can click on the LIGHT-BULB to get a list of
HINTS to resolve this particular error, which may or may not work!
SYNTAX WARNING:
marked by an orange triangular exclamation sign. Unlike errors, warnings may or may not
cause problems. Try to fix these warnings as well. But you can RUN your program with
warnings.
Objective:
Introduction:
An algorithm is a step-by-step set of instructions that provides a solution for a problem. The
flow chart is a diagram that can be used to represent an algorithm. The most commonly used
symbols in the flow charts are shown in the following table.
Indicates flowchart
Connector connection to another
symbol
Microsoft Visio is a diagramming application and is part of Microsoft Office 365 applications.
To access Visio on you Microsoft 365 account, you can use the following link:
www.office.com/launch/visio. You may also log into your account on office.com and locate
Visio link using the App launcher on the top left corner of your window. To start working on
Visio:
1. From the main window, click on Flowchart Template as shown in the following figure:
2. From Design menu, you can change the theme and colors as shown in the following
figure:
Lab Exercises:
1. Draw a flowchart for finding the greatest number among two numbers and print the
result.
2. Draw a flowchart for finding whether a number is odd or even and print the result.
3. Draw a flowchart for printing the first 10 even numbers.
4. Draw a flowchart for calculating the average from 20 exam scores and print the result
Challenging Problems:
1. Draw a flowchart for checking whether a number n is prime or not and print the result.
2. Draw a flowchart for finding and printing the first 10 number in the Fibonacci sequence.
Objective:
Introduction:
In this lab, we will introduce the first Java program that displays output messages on the
screen. Figure 1 shows a program that displays a line of text on the screen using three
different Java print methods. Note that line numbers at the beginning of each line of code is
not part of the Java program. Line 1 and 2 show single-line comments while lines 17-19 show
a multiple-line comment.
The second Java program reads, or inputs an integer typed by the user through the keyboard.
Many useful methods used to read different types of inputs are members of the Scanner
class from the package named java.util that is part of Java API (Java Application
Programming Interface).
Figure 2 shows a program that reads an integer from the user and then displays the integer
using printf method. Line 1 shows the import declaration that is required to use class
Scanner. Line 7 creates a Scanner object to use methods of the class to read characters
typed by the user at the keyboard.
A syntax error occurs when the compiler finds code that violates Java’s language rules or
syntax. Syntax errors are also called compilation errors because the compiler detects these
errors when compiling the program. When a syntax error is detected, the compiler issues an
error message.
A logical error is an error in the way a program works. The program can execute but produces
incorrect results.
• A compilation error occurs if a public class’s filename is not exactly the same name as
the class followed by the .java extension.
• It is a syntax error if braces do not occur in matching pairs.
• Placing an import declarations inside of after a class declaration is a syntax error.
• Forgetting to include an import declarations for a class that must be imported results in
a compilation error.
• It is a good practice to begin your program with a comment that states the purpose of the
program and the author.
• Use blank lines and indentation in your program to enhance readability.
• By convention, begin the class name with a capital letter and capitalize the first letter of
each word they include (e.g., SampleClassName). This naming convention is known as
camel case.
• Indent the entire body of each class declaration one level between the braces that delimit
the class. IDEs typically indent code for you. The Tab key may also be used to indent
code.
• Indent the entire body of each method declaration one level between the braces that
define the method’s body.
• Place a space after each comma (,) in an argument list to make programs more readable.
• Declare each variable in its own declaration to allow a descriptive comment to be inserted
next to each variable.
• Choosing meaningful variable names helps a program to be self-documenting.
• By convention, variable-name identifier use the camel-case naming convention with a
lowercase first letter (i.e. firstNumber).
Write a Java application that reads two integers and determines whether if the first integer is
divisible by the second integer and prints the quotient. If the first number is not divisible by
the second number, the program prints the remainder.
Sample Output 1:
Enter first integer: 10
Enter second integer: 5
10 is divisible by 5
10 / 5 = 2
Sample Output 2:
Enter first integer: 10
Enter second integer: 3
When 10 is divided by 3, the remainder is 1
Challenging Problems:
3. Write a Java application that inputs a 5-digit number from the user, separates the number
into individual digits, then prints the sum of the digits. For example, if the user types the
number 12345, the program should print sum = 15. Assume the user enters the correct
number of digits.
4. Write a Java application that add two 2-bit binary numbers.
5. Write a Java application that converts a 3-bit binary number to decimal.
6. Write a Java application that reverse a 3-digit decimal number.
7. Write a Java application that reads an integer n and computes the value n + nn + nnn. For
example, if the user inputs 5, you should print the value of 5 + 55 + 555.
Objective:
Introduction:
Simple conditions are expressed in terms of the relational operators where each expression
tests only one condition. In this lab we will discover the logical operators that enable you to
form more complex conditions by combining simple conditions.
Java has three types of section statements. In this lab, we will learn how to use two types of
selection statements.
1- Single selection statement: if statement either selects an action, if the condition is
true, or skips it, if the condition is false.
(selects or ignores a single action/group of actions)
2- Double selection statement: if…else statement selects an action if the condition is
true and performs a different action if the condition is false.
(selects between two different actions/group of actions)
The last topic to be explained in this lab is switch statement that performs different actions
based on the possible values of a constant integral expression.
Logical Operators :
Logical operators are used to check whether an expression is true or false. They are used in
decision making.
Operator
Operator Example Meaning
name
true only if both
expression1 && expression2 expression1 and
&& Logical AND
expression2 are
true.
true if either
expression1 || expression2 expression1 or
|| Logical OR
expression2 is
true
true if expression
! Logical NOT !expression is false and vice
versa.
if (condition)
statement;
or
if (condition) {
block of statements;
}
Flowchart of single-selection if statement:
if (condition)
{statement/s;}
else
{statement/s;}
if (condition)
{statement/s;}
else
{if (condition)
{statement/s;}
else
{if (condition)
{statement/s;}
else
{statement/s;}
}
}
switch (expression)
{
case value1:
Statement/s;
break; //optional
case value2 :
Statement/s;
break; //optional
case value3 :
Statement/s;
break; //optional
…
default :
Statement/s
break; //optional
}
• In a nested if...else statement, ensure that you test for all possible cases.
• Placing a semicolon after the condition in an if or if...else statement leads to a logic error
in single-selection if statements and a syntax error in double-selection if...else statements
(when the if-part contains an actual body statement).
• Forgetting the left and/or right parenthesis for the condition in an if statement is a syntax
error.
• Confusing the equality operator, ==, with the assignment operator, =, can cause a logic
error or a syntax error.
• Use expressions of the same type for the second and third operands of the ?: operator to
avoid subtle errors.
• In expressions using &&, a condition—we’ll call this the dependent condition—may require
another condition to be true for the dependent condition’s evaluation to be meaningful. In
this case, the dependent condition should be placed after the && operator to prevent
errors. Consider the expression (i != 0) && (10 / i == 2). The dependent condition (10/i==2)
must appear after the && to prevent the possibility of division by zero.
• Indent both body statements of an if...else statement. Most IDEs do this for you.
• If there are several levels of indentation, each level should be indented the same additional
amount of space.
• Conditional expressions are more difficult to read than if…else statements and should be
used to replace only simple if…else statements that choose between two values.
• Although each case and the default case in a switch can occur in any order, place the default
case last. When the default case is last, the break for that case is not required.
• Forgetting a break statement when one is needed in a switch is a logic error.
• In a switch statement, ensure that you test all possible values of the controlling expression.
1- Write a Java application that reads three numbers from the user, then prints the
greatest number.
Sample Output :
Enter first number: 52
Enter second number: 87
Enter third number: 78
2- Write a Java application that takes a year from the user, then prints whether that
year is a leap year or not.
Sample Output 1:
Enter a year: 2020
2020 is a leap year
Sample Output 2:
Enter a year: 2022
2020 is not a leap year
Sample Output :
Challenging Problems:
8. Write a Java application that will take a four digit number from the user, then prints a new
number with digits reversed as of original one
Objective:
Introduction:
An iteration statement (looping) allows you to specify that a program should repeat an action
while some condition remains true. In this lab we will learn how to use two formulating
algorithms . The first one is Counter-controlled iteration, the second one is Sentinel-controlled
iteration. In addition, we will learn how to compound the assignment operators as well as how
to use the increment (++) and decrement(- -) operators.
while (condition)
{
block of statements;
}
1- Counter-controlled iteration:
Uses a variable called a counter (or control variable) to control the number of
times a set of statements execute. It is often called definite iteration, because the
number of iterations is known before the loop begins executing.
counter =0
while (counter < number of iterations)
{
block of statements;
counter = counter +1;
}
2- Sentinel-controlled iteration:
A special value called a sentinel value (also called a signal value, a dummy
value or a flag value) is used to indicate “end of data entry.”. The sentinel value must
be chosen that cannot be confused with an acceptable input value.
input value
while (value != stopping value)
{
block of statements;
input value;
}
where operator is one of the binary operators +, -, *, / or % and the same variable name is
used can be written in the form
Java provides two unary operators for adding 1 to or subtracting 1 from the value of a
numeric variable. These are the unary increment operator, ++, and the unary decrement
operator, --.
Sample
Operator Operator name Explanation
expression
• Not providing in the body of a while statement an action that eventually causes the
condition in the while to become false normally results in a logic error called an infinite
loop (the loop never terminates).
• Using the value of a local variable before it’s initialized results in a compilation error. All
local variables must be initialized before their values are used in expressions.
• To avoid error, initialize each total and counter, either in its declaration or in an assignment
statement. Totals are normally initialized to 0. Counters are normally initialized to 0 or 1,
depending on how they’re used.
• Assuming that integer division rounds (rather than truncates) can lead to incorrect results.
For example, 7÷ 4, which yields 1.75 in conventional arithmetic, truncates to 1 in integer
arithmetic, rather than rounding to 2.
• Omitting the braces that delimit a block can lead to logic errors, such as infinite loops. To
prevent this problem, some programmers enclose the body of every control statement in
braces, even if the body contains only a single statement.
• A cast operator can be used to convert between primitive numeric types, such as int and
double. Casting to the wrong type may cause compilation errors or runtime errors.
• Using floating-point numbers in a manner that assumes they’re represented precisely can
lead to incorrect results.
• Attempting to use the increment or decrement operator on an expression other than one
to which a value can be assigned is a syntax error. For example, writing ++(x + 1) is a
syntax error, because (x + 1) is not a variable.
Lab Exercise:
4- Write a Java application that find the summation of numbers from 1 to a given number.
Sample Output :
Enter a number: 10
The summation of numbers from 1 to 10 = 55
5- Write a Java application to display the pattern like right angle triangle of a given
number.
Sample Output :
Enter a number: 5
1
12
123
1234
12345
Objective:
Introduction:
In this lab we will study how to use the do...while statement which is similar to the while
iteration statement. In the while, the program tests the loop-continuation condition at the
beginning of the loop, before executing its body; if the condition is false, the body never
executes. The do...while statement tests the loop-continuation condition after executing the
loop’s body; therefore, the body always executes at least once.
Java provides the for iteration statement, which specifies the counter-controlled-
iteration details in a single line of code. The for statement specifies all the details of counter-
controlled iteration in its header. When the for statement begins executing, its control variable
is declared and initialized. If the loop-continuation condition is initially true, the body executes.
After executing the loop’s body, the increment expression executes. Then the loop-
continuation test is performed again to deter-mine whether the program should continue with
the next iteration of the loop.
do
{
block of statements;
}
while (condition)
statement/s Required
• Using an incorrect relational operator or an incorrect final value of a loop counter in the
loop-continuation condition of an iteration statement can cause an off-by-one error.
• Using the final value and operator <= in a loop’s condition helps avoid off-by-one errors.
For a loop that outputs 1 to 10, the loop-continuation condition should be counter <= 10
rather than counter < 10 (which causes an off-by-one error) or counter < 11 (which is
correct). Many programmers prefer so-called zero-based counting, in which to count 10
times, counter would be initialized to zero and the loop-continuation test would be counter
< 10.
• When a for statement’s control variable is declared in the initialization section of the for’s
header, using the control variable after the for’s body is a compilation error.
• Placing a semicolon immediately to the right of the right parenthesis of a for header makes
that for’s body an empty statement. This is normally a logic error.
• Infinite loops occur when the loop-continuation condition in an iteration statement never
becomes false. To prevent this situation in a counter-controlled loop, ensure that the
control variable is modified during each iteration of the loop so that the loop-continuation
condition will eventually become false. In a sentinel-controlled loop, ensure that the
sentinel value is able to be input.
• Using an incorrect relational operator in the loop-continuation condition ofa loop that
counts downward (e.g., using i <= 1 instead of i >= 1 in a loop counting down to 1) is
usually a logic error.
• Do not use equality operators (!= or ==) in a loop-continuation condition if the loop’s control
variable increments or decrements by more than 1. For example, consider the for
statement header for (int counter = 1; counter != 10; counter += 2). The loop-continuation
test counter != 10 never becomes false (resulting in an infinite loop) because counter
increments by 2 after each iteration.
• For readability limit the size of control-statement headers to a single line if possible.
Lab Exercise:
6- Write a Java program that asks the user for an integer number, then prints its multiplication
table.
Sample Output :
Enter an integer number: 5
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
7- Write a Java program that asks the user for an integer number, then prints its factorial.
Sample Output 1 :
Enter an integer number: 5
5! = 120
Sample Output 2 :
Enter an integer number: 7
7! = 5040
Challenging Problems:
1. In Java, we can create an ATM program for representing ATM transection. In the ATM
program, the user has to select an option from the options displayed on the screen.
The options are related to withdraw the money, deposit the money, check the balance,
and exit.
To withdraw the money, we simply get the withdrawal amount from the user and
remove that amount from the total balance and print the successful message.
To deposit the money, we simply get the deposit amount from the user, add it to the
total balance and print the successful message.
To check balance, we simply print the total balance of the user.
2. Write a Java program to display the following character rhombus structure.
3. In Java, we can create an ATM program for representing ATM transection. In the ATM
program, the user has to select an option from the options displayed on the screen.
The options are related to withdraw the money, deposit the money, check the balance,
and exit.
To withdraw the money, we simply get the withdrawal amount from the user and
remove that amount from the total balance and print the successful message.
To deposit the money, we simply get the deposit amount from the user, add it to the
total balance and print the successful message.
To check balance, we simply print the total balance of the user.
Objective:
Introduction:
An array is a group of elements that can hold values of the same type. An array is an object,
so it is considered as reference type. The elements of the array can be either primitive types
or reference types.
Strings are an object variable type. They are immutable, which means they can-not be
changed. That doesn’t mean you can never modify a string when writing a program, it just
means that when you’re modifying it, it’s actually creating a new string each time a change
is made. Strings are stored as arrays of chars where each character has an index that can
be recall with. Their indexing is 0-based, so the first character of the string is at index 0. If a
string is used without being stored in a variable, such as in a print statement, it is referred to
as a literal. Strings are objects made from the String class which associated with some
useful and easy to use methods.
Syntax of Arrays:
The array_type can be primitive or reference type and the array_size can be replaced
by a literal value or a constant variable. When the array is created using new keyword, array
elements are initialized to the default values depending on the array type (i.e. 0 for int array,
False for boolean array, null for an array of references, etc). The array can be also created
and initialize using array initializer as follows:
Every array object has its own length stored in a length instance variable.
1. s1.length(); This method will return the number of characters in string s1.
2. s1.equals(s2); This method is Boolean method and will return true if string s1 is
equal to string s2.
3. S1.replace(‘char1’,’char2’); This method will replace every existence of char1 in
the string with char2.
4. s1.reverse(); This method will reverse the string s1.
5. s1.charAt(index);This method will return the character located in the string s1 at
the given index.
• An index must be an int value or a value of a type that can be promoted to int (i.e. byte,
short, or char but not long). Otherwise, a compilation error occurs.
• In an array declaration, specifying the number of elements in the square brackets of the
declaration (e.g. int[12] c;) is a syntax error.
• Declaring multiple array variables in a single declaration can lead to subtle errors.
Consider the declaration int[] a, b, c;. If a, b and c should be declared as array
variables, then this declaration is correct. However, if only a is intended to be an array
variable, and b and c are intended to be individual int variables, then this declaration is
incorrect. The declaration int a[], b, c; would achieve the desired result.
• Assigning a value to a final variable after it has been initialized is a compilation error.
Similarly, attempting to access the value of a final variable before it is initialized results
in a compilation error.
• Any attempt to access an element outside that range of indices results in a runtime error
that’s known as an ArrayIndexOutOfBoundsException.
• Using java strings methods has different types and argument, make sure to follow the
exact format to prevent syntax and runtime errors.
• When two separate objects that contains the same value are compared with == the
result will be false, instead method equals must be used to determine whether the two
objects have the same content.
• For readability, keep each declaration on a separate line, and include a comment
describing the variable being declared.
• Constant variables also are called named constants. They often make programs more
readable than programs that use literal values (e.g. 10). A named constant such as
ARRAY_LENGTH clearly indicates its purpose, whereas a literal value could have different
meanings based on its context.
• Multiword named constants should have each word separated from the next with
underscore (_) as in ARRAY_LENGTH.
• Java provides many strings methods, using them will save time and effort. The following
link give more details about java strings methods:
• https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Sample Output:
2- Write a java program that reads two text value from the user and do some string
manipulation. The strings should be stored in object of type String s1 and s2. You
need to show the following menu for the use:
1. Reverse
2. Remove a character
3. Number of Uppercase
4. Number of digits
5. Compare two strings
6. Exit
:
• Reverse: Takes a string and reverse it.
• Remove a character: Takes a character and a string, and removes all occurrences of
that character in the string.
• Number of uppercase letters: Takes a string and prints the number of Uppercase letters
in the string.
• Number of digits: Takes a string and prints the number of digits in the string.
• Compare two strings: Checks whether two strings are equal or not. Use string
comparison methods ( s1.equals(s2) or s1.compareTo(s2)).
10. Write a Java application that simulate the Tic Tac Toe game. Here are the requirements:
a. The first player is the user who inputs the move using the keyboard and the second
user is the computer who chooses the move randomly.
b. The board should be printed out every time a player makes a move.
c. You should be able to accept input of the player position and then place a symbol on
the board.
You can use a 3-by-3 array to represent the board. You can assume that 1 represents X,
0 represents O, and -1 represents an empty position. Use methods and control statements
in your program.
Objective:
Introduction:
Methods help you build a large program from small, simple units. Methods make program
development more manageable using divide and conquer approach, it also promotes software
reusability by using existing methods to build new programs and help the programmer to avoid
repeating code.
Random number generation is a very useful to implement programs that simulate real-life
application. The class SecureRandom that is available in the package java.security of
the Java API has several methods that can generate random values of different types. To
generate integers at random from sets of values other than ranges of consecutive integers,
you can use the following general statement:
Where shiftValue specifies the first number in the range of values, differenceBetweenValues
specifies the difference between consecutive values in the sequence, and scalingFactor
specifies how many numbers are in the range.
Method declaration:
// method body
Lab Exercise:
Write a Java application that performs the following operations based on a user choice:
1. Reverse the digits of a number.
2. Check if a number is palindrome.
3. Check if a number is a perfect number.
HINT: you can call a method inside another method to avoid using repeated code and take
advantage of software usability.
Sample Output:
Invalid choice!
Thank you!
Challenging Problems:
Objective:
Introduction:
This lab demonstrates how to pass arrays and individual array elements as arguments to
methods.
1- Pass-by-value:
When an argument is passed by value, a copy of the argument’s value is passed to the
called method. The called method works exclusively with the copy. Changes to the called
method’s copy do not affect the original variable’s value in the caller.
2- Pass-by-reference:
When an argument is passed by reference, the called method can access the argument’s
value in the caller directly and modify that data, if necessary.
To pass an array argument to a method, specify the name of the array without any brackets.
method_name(array_name);
• An index must be an int value or a value of a type that can be promoted to int (i.e. byte,
short, or char but not long). Otherwise, a compilation error occurs.
• Passing references to arrays, instead of the array objects themselves, makes sense for
performance reasons
Lab Exercise:
Write a Java application called GradeStatistics, that keeps the grades of 20 students and
displays the average, minimum, maximum, standard deviation, and a histogram of the grades.
The program should store the grades in an array of type int. Your program should include
the following methods:
• initArray: the method takes an integer array and initialize it with random numbers
in the range 0 to 99.
• maximum: the method takes an integer array and returns the maximum grade.
• minimum: the method takes an integer array and returns the minimum grade.
• average: the method takes an integer array and returns the average grade as double.
• standardDev: the method takes an integer array and returns the standard deviation
of the grades as double. The standard deviation is given as
.
• printArray: the method takes an integer array and prints the array elements.
• computeHistogram: the method takes an integer array and returns a new integer
array. The method counts the frequency of each grade and stores the count value in
the new array. Assume the first element of the new array stores the frequency of
grades in the range 0 to 9, the second element stores the frequency of grades in the
range 10 to 19, etc.
• printHistogram: the method takes an integer array and prints the histogram
horizontally. Hint: you can call method computeHistogram.
Sample Output:
The grades are:
79 87 41 5 4 96 78 72 97 21 13 57 73 90 41 21 94 72 75 81
Write a Java application that simulate the Tic Tac Toe game. Here are the requirements:
a) The first player is the user who inputs the move using the keyboard and the second
user is the computer who chooses the move randomly.
b) The board should be printed out every time a player makes a move.
c) You should be able to accept input of the player position and then place a symbol
on the board.
You can use a 3-by-3 array to represent the board. You can assume that 1 represents X,
0 represents O, and -1 represents an empty position. Use methods and control statements
in your program.
Objective:
Introduction:
Classes: A class is a user defined prototype from which objects are created. It represents
the set of methods that are common to all objects of one type. In general, class declarations
can include these components, in order:
1. Modifiers: A class can be public or has default access.
2. class keyword: class keyword is used to create a class.
3. Class name: Class names begin with an uppercase letter, and method and
variable names begin with a lowercase letter.
4. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provides the state
of the class and its objects, and methods are used to implement the behavior of the class
and its objects. Its declaration uses the same name as the class and it has no return type.
Objects: A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of:
1. State: It is represented by attributes of an object. It also reflects the properties of
an object.
2. Behavior: It is represented by methods of an object. It also reflects the response
of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.
• We prefer to list a class’s fields first, so that, as you read the code, you see the names
and types of the variables before they’re used in the class’s methods.
• Place a blank line between method declarations to separate the methods and enhance
program readability.
Lab Exercise:
Create a class called Student that has three instance variables: studentName (type String),
studentId (type int) and studentGpa (type double). Your class should have the following:
Student
-studentName : String
-studentId : int
-studentGpa : double
Write a test application named StudentTest that demonstrates class Student capabilities. In
the main method, do the following:
• Input two students’ data (name, id and gpa) from the user.
• Create two Student objects. Initialize the objects using the data entered by the user.
• Display both students’ data information.
• Compare both students gpa and display which one has higher gpa than the other
Sample Output
Enter student#1 info:
Name: Khalid Ali
ID: 2221011234
GPA: 2.54
Student’s name is Khalid Ali, ID number is 2221011234 with a GPA of 2.54
Challenging Problems:
Create a class called FindRoots that find the roots of a quadratic function ax2 + bx + c. where
a, b and c are double numbers and a can’t be 0. The class includes:
• Three instance variables: a (type double), b (type double) and c (type double).
• A constructor that initializes the three instance variables.
• set and get methods for each instance variable.
• A method getDiscriminant that will calculate and return the discriminant.
• A method calRoots that will calculate and display the roots of a quadratic function.
• A method DisplayQuadFunction that will return a string representation of a quadratic
function.
Sample output 1:
Enter the coefficients a, b and c of quadratic function
a: 1
b: 5
c: 6
Quadratic function: 1.0*x^2 + 5.0*x + 6.0
There are 2 roots: -2.00 and -3.00
Sample output 2:
Enter the coefficients a, b and c of quadratic function
a: 1
b: 2
c: 1
Quadratic function: 1.0*x^2 + 2.0*x + 1.0
There is one root: -1.00
Sample output 3:
Enter the coefficients a, b and c of quadratic function
a: 2
b: 1
c: 5
Quadratic function: 2.0*x^2 + 1.0*x + 5.0
No roots, discriminant < 0.