Tag Archives: java

Java || Simple Tic Tac Toe Game Sample Code GUI

The following is another homework assignment which was presented in an intro to Java class. This program was used to provide more practice creating a graphical user interface.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

JFrame
JMenu
JButtons
JPanel
JOptionPane
How To Play Tic-Tac-Toe
Special Fonts For This Game - Click Here To Download
Executable .Jar File - Click Here To Download & Play

This program features a graphical user interface (GUI) which has nine buttons arranged in a square. A user plays the game by clicking the mouse in a available button. The game then places a symbol on the clicked button alternating between the letters “X” and an “O.”

The game begins by clicking on the “New Game” button. This action will clear away any text on the 9 game buttons. The 9 game buttons are still disabled, but the radio button is enabled. This means someone must select who plays first: “X” or “O.” After selecting the starting player then the 9 game buttons become enabled.

When a player clicks on one of the 9 available game buttons, the text on that button will change into an “X” or an “O.” The game stops when one of the two players has 3 identical symbols in a row, a column, or a diagonal. When there is such a winner, the symbol of the winner is displayed to the screen. Sometimes all 9 game buttons have been clicked on but there is still no winner. In that case the text “Tie” is displayed to the screen.

The two buttons “New Game” and “Quit” remain enabled at all times. Clicking on “Quit” will close the window.

This program was implemented into 3 different files, so the code for this program will be broken up into 3 sections. The three-file solution always has one file (the driver) which contains the “main” function. Another file contains the implementation of the graphical user interface (GUI), and the last file contains logic, which in this case is the game algorithms.

==== File #1 – TicTacToe.java ====

==== File #2 – GUI.java ====

This is the GUI (graphical user interface) class for a three-file solution which implements the game of tic tac toe. The sole purpose of this source code is to define the GUI and call methods in the BusinessLogic class when needed.

==== File #3 – BusinessLogic.java ====

This is the BusinessLogic class for a three-file solution which implements the game of tic tac toe. The is the class containing algorithms.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

This program uses custom fonts. To obtain those fonts, click here!

Click here to download & play the executable .jar file.

SAMPLE SCREENSHOT:
(click to enlarge)

Java || Snippet – How To Find The Highest & Lowest Numbers Contained In An Integer Array

This page will consist of a simple demonstration for finding the highest and lowest numbers contained in an integer array.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Integer Arrays
For Loops
Custom Setw/Setfill In Java

Finding the highest/lowest values in an array can be found in one or two ways. The first way would be via a sort, which would obviously render the highest/lowest numbers contained in the array because the values would be sorted in order from highest to lowest. But a sort may not always be practical, especially when you want to keep the array values in the same order that they originally came in.

The second method of finding the highest/lowest values is by traversing through the array, literally checking each value it contains one by one to determine if the current number which is being compared truly is a target value or not. That method will be displayed below.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Welcome to My Programming Notes' Java Program.

Original array values:
36 35 46 86 86 58 44 38 79 52 27 78 65 79
------------------------------------------------------------
These are the highest and lowest array values:
Highest: 86
Lowest: 27

Java || Snippet – How To Input Numbers Into An Integer Array & Display Its Contents Back To User

This snippet demonstrates how to place numbers into an integer array. It also shows how to display the contents of the array back to the user via stdout.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Integer Arrays
For Loops
Final Variables


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Welcome to My Programming Notes' Java Program.

How many items do you want to place into the array?: 5

Enter item #1: 12
Enter item #2: 43
Enter item #3: 5
Enter item #4: 643
Enter item #5: 2321

The current items inside the array are:
Item #1: 12
Item #2: 43
Item #3: 5
Item #4: 643
Item #5: 2321

Java || Snippet – How To Convert A Decimal Number Into Binary

This page will demonstrate how to convert a decimal number (i.e a whole number) into its binary equivalent. So for example, if the decimal number of 25 was entered into the program, it would display the converted binary value of 11001.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

How To Count In Binary
The "Long" Datatype - What Is It?
Methods (A.K.A "Functions") - What Are They?
While Loops
Online Binary to Decimal Converter - Verify For Correct Results

If you are looking for sample code which converts binary to decimal, check back here soon!


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
Note: The code was compiled 3 separate times to display different output

====== RUN 1 ======

Welcome to My Programming Notes' Java Program.

Please enter an integer value: 5

The integer value of 5 = 101 in binary

====== RUN 2 ======

Welcome to My Programming Notes' Java Program.

Please enter an integer value: -25

The integer value of -25 = -11001 in binary

====== RUN 3 ======

Welcome to My Programming Notes' Java Program.

Please enter an integer value: 12345678910

The integer value of 12345678910 = 1011011111110111000001110000111110 in binary

Java || Searching An Integer Array For A Target Value

Here is another actual homework assignment which was presented in an intro to programming class which was used to introduce more practice using integer arrays.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Integer Arrays
For Loops
Methods (A.K.A "Functions") - What Are They?
Final Variables
If/Else Statements

This is a small and simple program which demonstrates how to search for a target value which is stored in an integer array. This program first prompts the user to enter five values into an int array. After the user enters all the values into the system, it then displays a prompt asking the user for a search value. Once it has a search value, the program searches through the array looking for the target value; and wherever the value is found, the program display’s the current array index in which that target value is located. After it displays all the locations where the target value resides, it display’s the total number of occurrences the search value was found within the array.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output:
Note: The code was compiled 3 separate times to display the different outputs its able to produce

====== RUN 1 ======

Welcome to My Programming Notes' Java Program.

Please enter 5 integer values:
#1: 25
#2: 25
#3: 25
#4: 25
#5: 25
Please enter a search value: 25

25 was found at array index #0
25 was found at array index #1
25 was found at array index #2
25 was found at array index #3
25 was found at array index #4

The total occurrences of value 25 within the array is: 5

====== RUN 2 ======

Welcome to My Programming Notes' Java Program.

Please enter 5 integer values:
#1: 8
#2: 19
#3: 97
#4: 56
#5: 8
Please enter a search value: 8

8 was found at array index #0
8 was found at array index #4

The total occurrences of value 8 within the array is: 2

====== RUN 3 ======

Welcome to My Programming Notes' Java Program.

Please enter 5 integer values:
#1: 78
#2: 65
#3: 3
#4: 45
#5: 89
Please enter a search value: 12

The total occurrences of value 12 within the array is: 0

Java || Find The Prime, Perfect & All Known Divisors Of A Number Using A For, While & Do/While Loop

This program was designed to better understand how to use different loops which are available in Java, as well as more practice using objects with classes.

This program first asks the user to enter a non negative number. After it obtains a non negative integer from the user, the program determines if the user obtained number is a prime number or not, aswell as determining if the user obtained number is a perfect number or not. After it obtains its results, the program will display to the screen if the user inputted number is prime/perfect number or not. The program will also display a list of all the possible divisors of the user obtained number via stdout.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Class Objects - How TO Use
Constructors - What Are They?
Do/While Loop
While Loop
For Loop
Modulus
Basic Math - Prime Numbers
Basic Math - Perfect Numbers
Basic Math - Divisors


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output:

Enter a number: 41

Input number: 41
41 is a prime number.
41 is not a perfect number.
Divisors of 41 are: 1, and 41

Do you want to input another number?(Y/N): y
------------------------------------------------------------
Enter a number: 496

Input number: 496
496 is not a prime number.
496 is a perfect number.
Divisors of 496 are: 1, 2, 4, 8, 16, 31, 62, 124, 248, and 496

Do you want to input another number?(Y/N): y
------------------------------------------------------------
Enter a number: 1858

Input number: 1858
1858 is not a prime number.
1858 is not a perfect number.
Divisors of 1858 are: 1, 2, 929, and 1858

Do you want to input another number?(Y/N): y
------------------------------------------------------------
Enter a number: -9

Sorry, but the number entered is less than the allowable limit.
Please try again.....

Enter an number: 12

Input number: 12
12 is not a prime number.
12 is not a perfect number.
Divisors of 12 are: 1, 2, 3, 4, 6, and 12

Do you want to input another number?(Y/N): n
------------------------------------------------------------
BYE!

Java || Find The Average Using an Array – Omit Highest And Lowest Scores

This page will consist of two programs which calculates the average of a specific amount of numbers using an array.

REQUIRED KNOWLEDGE FOR BOTH PROGRAMS

Double Data Type
Final Variables
Arrays
For Loops
Assignment Operators
Basic Math - How To Find The Average

====== FIND THE AVERAGE USING AN ARRAY ======

The first program is fairly simple, and it was used to introduce the array concept. The program prompts the user to enter the total amount of numbers they want to find the average for, then the program displays the answer to them via stdout.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

ARRAY
Notice the array declaration on line #13. The type of array being used in this program is a dynamic array, which has the ability to store up to 100 integer elements in the array. You can change the number of elements its able to store to a higher or lower number if you wish.

FOR LOOP
Lines 27-32 contains a for loop, which is used to actually store the data inside of the array. Without some type of loop, it is virtually impossible for the user to input data into the array; that is, unless you want to add 100 different println statements into your code asking the user to input data. Line 31 uses the assignment operator “+=” which gives us a running total of the data that is being inputted into the array. Note the loop only stores as many elements as the user so desires, so if the user only wants to input 3 numbers into the array, the for loop will only execute 3 times.

Once compiled, you should get this as your output:

Welcome to My Programming Notes' Java Program.

How many numbers do you want to find the average for?: 4
Enter value #1: 21
Enter value #2: 24
Enter value #3: 19
Enter value #4: 17
The average of the 4 numbers is 20.25

====== FIND THE AVERAGE – OMIT HIGHEST AND LOWEST SCORES ======

The second program is really practical in a real world setting. We were asked to create a program for a fictional competition which had 6 judges. The 6 judges each gave a score of the performance for a competitor in a competition, (i.e a score of 1-10), and we were asked to find the average of those scores, omitting the highest/lowest results. The program was to store the scores into an array, display the scores back to the user via stdout, display the highest and lowest scores among the 6 obtained, display the average of the 6 scores, and finally display the average adjusted scores omitting the highest and lowest result.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

FINAL
A final variable was declared and used to initialize the array (line 7). This was used to initialize the size of the array.

FOR LOOPS
Once again loops were used to traverse the array, as noted on lines 24, 51 and 73. The final variable was also used within the for loops, making it easier to modify the code if its necessary to reduce or increase the number of available judges.

HIGHEST/LOWEST SCORES
This is noted on lines 35-45, and it is really simple to understand the process once you see the code.

OMITTING HIGHEST/LOWEST SCORE
Lines 73-81 highlights this process. The loop basically traverses the array, skipping over the highest/lowest elements.

Once compiled, you should get this as your output

Welcome to My Programming Notes' Java Program.

Judges, enter one score each for
the current competitor: 123 453 -789 2 23345 987

These are the scores from the 6 judges:
The score for judge #1 is: 123.0
The score for judge #2 is: 453.0
The score for judge #3 is: -789.0
The score for judge #4 is: 2.0
The score for judge #5 is: 23345.0
The score for judge #6 is: 987.0

These are the highest and lowest scores:
Highest: 23345.0
Lowest: -789.0
The average score is: 4020.1666666666665
The average adjusted score omitting the highest and lowest result is: 391.25

Java || Display Today’s Date Using a Switch Statement

If statements, char’s and strings have been previously discussed, and this page will be more of the same. This program will demonstrate how to use a switch statement to display today’s date, converting from mm/dd/yyyy format (i.e 6/17/12) to formal format (i.e June 17th, 2012).

This same program can easily be done using if statements, but sometimes that is not always the fastest programming method. Switch statements are like literal light switches because the code “goes down a line” to check to see which case is valid or not, just like if statements. You will see why switches are very effective when used right by examining this program.

====== TODAY’S DATE USING A SWITCH ======

So to start our program out, lets define the variables.


Notice on line 6 there is a variable named “cin.” This program uses the scanner class to obtain data from the user. Click here for various examples demonstrating how to obtain data from the user using the scanner class.

We also declared three other variables, named “month, day, and year.” You should always name your variables something descriptive, as well as initializing them to a starting value.

Next we get data from the user for the month, day, and year variables. This process is demonstrated below:


Notice the format that the user will input the data in. They will input data in mm/dd/yyyy format, and using the “cin” variable will make that possible.

So after obtaining data from the user, how will the program convert numbers into actual text? Next comes the switch statements.


Line 2 contains the switch declaration, and its comparing the variable of “month” to the 12 different cases that is defined within the switch statement. So this piece of code will “go down the line” comparing to see if the user obtained data is any of the numbers from 1 to 12, as defined in the switch statement. If the user chooses a number which does not fall between 1 thru 12, the “default” case will be executed, prompting the user that the data they entered was invalid, which can be seen in line 40. Notice line 42 has an exit code. This program will force an exit whenever the user enters invalid data.

Line 6 is also very important, because that forces the computer to “break” away from the selected case whenever it is done examining that specific piece of code. It is important to add the break statement in there to avoid errors, which may result if the program does not break away from the current statement in which it is examining. Try compiling this code removing the “break” statements and see what happens!

Next we will add another switch statement in order to convert the day of the month to have a number suffix (i.e displaying the number in 1st, 2nd, 3rd format). This is very similar to the previous switch statement


This block of code is very similar to the previous one. Line 2 is declaring the variable ‘day’ to be compared with the base cases; line 6 and so forth has the break lines, but line 4, 7 and 10 are different. If you notice, line 4, 7 and 10 are comparing multiple cases in one line. Yes, with switch statements, you can do that. Just like you can compare multiple values in if statements, the same can be done here. So this switch is comparing the number the user entered into the program, with the base cases, adding a suffix to the end of the number.

So far we have obtained data from the user, compared the month and day using switch statements and displayed that to the screen. Now all we have to do is output the year to the user. This is fairly simple, because the year is not being compared, you are just simply using a system print to display data to the user.

So finally, adding all the above snippets together should give us the following code:

Once compiled, you should get this as your output:

Welcome to My Programming Notes' Java Program.

Please enter the current month: 7
Please enter the current day: 28
Please enter the current year: 2012

Todays date is:
July 28th, 2012

Java || Snippet – Custom Setw & Setfill Sample Code For Java

This page will consist of a brief implementation of setw/ios::width and setfill/ios::fill in Java.

If you are a C++ programmer, no doubt you have used the setw and setfill commands many times. It makes formatting output like this very clean and simple (see below).

Ending balance:................. $ 6433.47
Amount of deposits:............. $ 1750.00
Amount of withdrawals:.......... $ 420.00
Amount of interest earned:...... $ 103.47

But to my amazement, I could not find a very suitable replacement for the setw/setfill functions in Java. Using simple for loops, the methods provided on this page has the ability to mimic both functions which are available in C++.

Included in the sample code are the following:

== SETW ==

(1) right - Justifies string data of size "width," filling the width to the start of the string with whitespace

(2) left - Justifies string data of size "width," filling the width to the end of the string with whitespace

== SETFILL ==

(3) right - Justifies string data of size "width," filling the width to the start of the string with a filler character

(4) left - Justifies string data of size "width," filling the width to the end of the string with a filler character

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

Also, you must understand minimal object oriented programming to use this code!

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

===== DEMONSTRATION HOW TO USE =====

Use of the above snippet is similar to its C++ counterpart. Here is a sample program demonstrating its use.

Once compiled, you should get this as your output

Java || Whats My Name? – Practice Using Strings, Methods & Switch Statemens

Here is another actual homework assignment which was presented in an intro to programming class. This program highlights more use using strings, modules, and switch statements.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

How To Get String Input
If/Else Statements
Methods (A.K.A "Functions") - What Are They?
Switch Statements - How To Use Them
Equal - String Comparison

This program first prompts the user to enter their name. Upon receiving that information, the program saves input into a string called “firstName.” The program then asks if the user has a middle name. If they do, the user will enter a middle name. If they dont, the program proceeds to ask for a last name. Upon receiving the first, [middle], and last names, the program will append the first, [middle], and last names into a completely new string titled “fullName.” Lastly, if the users’ first, [middle], or last names are the same, the program will display that data to the screen via stdout. The program will also display to the user the number of characters their full name contains using the built in function “length.”


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
Note: The code was compiled five separate times to display the different outputs its able to produce

====== RUN 1 ======

Welcome to My Programming Notes' Java Program.

Please enter your first name: My
Do you have a middle name?(Y/N): y
Please enter your middle name: Programming
Please enter your last name: Notes

The total number of characters in your name is: 18
And your full name is My Programming Notes

====== RUN 2 ======

Welcome to My Programming Notes' Java Program.

Please enter your first name: Programming
Do you have a middle name?(Y/N): n
Please enter your last name: Notes

The total number of characters in your name is: 16
And your full name is Programming Notes

====== RUN 3 ======

Welcome to My Programming Notes' Java Program.

Please enter your first name: Notes
Do you have a middle name?(Y/N): y
Please enter your middle name: Notes
Please enter your last name: Notes

Your first and middle name are the same
Your middle and last name are the same
Your first and last name are the same

The total number of characters in your name is: 15
And your full name is Notes Notes Notes

====== RUN 4 ======

Welcome to My Programming Notes' Java Program.

Please enter your first name: My
Do you have a middle name?(Y/N): n
Please enter your last name: My

Your first and last name are the same

The total number of characters in your name is: 4
And your full name is My My

====== RUN 5 ======

Welcome to My Programming Notes' Java Program.

Please enter your first name: My
Do you have a middle name?(Y/N): z

Please press either 'Y' or 'N'
Program exiting...

Java || Count The Total Number Of Characters, Vowels, & UPPERCASE Letters Contained In A Sentence Using A ‘For Loop’

Here is a simple program, which demonstrates more practice using the input/output mechanisms which are available in Java.

This program will prompt the user to enter a sentence, then upon entering an “exit code,” will display the total number of uppercase letters, vowels and characters which are contained within that sentence. This program is very similar to an earlier project, this time, utilizing a for loop, strings, and user defined methods.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

How To Get String Input
If/Else Statements
For Loops
Methods (A.K.A "Functions") - What Are They?


QUICK NOTES:
The highlighted portions are areas of interest.

Notice line 22 contains the for loop declaration. The loop will continually loop thru the string, and will not stop doing so until it reaches an exit character, and the defined exit character in this program is a period (“.”). So, the program will not stop looping thru the string until it reaches a period.

Once compiling the above code, you should receive this as your output

Welcome to My Programming Notes' Java Program.

Enter a sentence, ending with a period:
My Programming Notes Is An Awesome Site.

Total number of upper case letters:........7
Total number of vowels:....................14
Total number of characters:................33

Java || Compute The Sum From A String Of Integers & Display Each Number Individually

Here is a simple program, which was presented in a Java course. This program was used to introduce the input/output mechanisms which are available in Java. This assignment was modeled after Exercise 2.30, taken from the textbook “Java How to Program” (early objects) (9th Edition) (Deitel). It is the same exercise in both the 8th and 9th editions.

Our class was asked to make a program which prompts the user to enter a non-negative integer into the system. The program was supposed to then extract the digits from the inputted number, displaying them each individually, separated by a white space (” “). After the digits are displayed, the program was then supposed to display the sum of those digits to the screen. So for example, if the user inputted the number “39465,” the program would output the numbers 3 9 4 6 5 individually, and then the sum of 27.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

How To Get String Input
If/Else Statements
Do/While Loops
For Loops
Methods (A.K.A "Functions") - What Are They?
ParseInt - Convert String To Integer
Substring
Try/Catch


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Welcome to My Programming Notes' Java Program.

Enter a non negative integer: 0

The digits are: 0 and the sum is 0

Do you have more data for input? (Y/N): y

------------------------------------------------
Enter a non negative integer: 39465

The digits are: 3 9 4 6 5 and the sum is 27

Do you have more data for input? (Y/N): y

------------------------------------------------
Enter a non negative integer: H3ll0 W0rld

H3ll0 W0rld is not a number...
Please enter digits only!

Do you have more data for input? (Y/N): y

------------------------------------------------
Enter a non negative integer: -98

-98 is a negative number...
Please enter positive digits only!

Do you have more data for input? (Y/N): y

------------------------------------------------
Enter a non negative integer: 19.87

19.87 is a decimal number...
Please enter positive whole numbers only!

Do you have more data for input? (Y/N): n

------------------------------------------------

BYE!

Java || Using If Statements, Char & String Variables

As previously mentioned, you can use the “int/float/double” data type to store numbers. But what if you want to store letters? Char and Strings help you do that.

===== SINGLE CHAR =====

This example will demonstrate a simple program using char, which checks to see if you entered the correctly predefined letter.

Notice in line 19 I declare the char data type, naming it “userInput.” I also initialized it as an empty variable. In line 26 I used an “If/Else Statement” to determine if the user inputted value matches the predefined letter within the program. I also used the “OR” operator in line 26 to determine if the letter the user inputted was lower or uppercase. Try compiling the program simply using this
if (userInput == 'a') as your if statement, and notice the difference.

The resulting code should give this as output

Please try to guess the letter I am thinking of: A
You have Guessed correctly!

===== CHECK IF LETTER IS UPPER CASE =====

This example is similar to the previous one, and will check if a letter is uppercase

Notice in line 26, an If statement was used, which checked to see if the user inputted data fell between letter A and letter Z. We did that by using the “AND” operator. So that IF statement is basically saying (in plain english)

IF ('userInput' is equal to or greater than 'A') AND ('userInput' is equal to or less than 'Z')

THEN it is an uppercase letter

The resulting code should give this as output

Please enter an UPPERCASE letter: p
p is not an uppercase letter

===== CHECK IF LETTER IS A VOWEL =====

This example will utilize more if statements, checking to see if the user inputted data is a vowel or not. This will be very similar to the previous example, utilizing the OR operator once again.

This program should be very straight forward, and its basically checking to see if the user entered data is the letter A, E, I, O, U or Y.

The resulting code should give the following output

Please enter a vowel: o
Correct, o is a vowel!

===== HELLO WORLD v2 =====

This last example will demonstrate using the string data type to print the line “Hello World!” to the screen.

The resulting code should give following output

Please enter a sentence: Hello World!
You entered: Hello World!

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

javac YOUR_CLASS_NAME.java

*** To run the compiled program, simply type this command:

java YOUR_CLASS_NAME

Java || Simple Math Using Int & Double

This page will display the use of int and double data types.

==== ADDING TWO NUMBERS TOGETHER ====

To add two numbers together, you will have to first declare your variables by doing something like this.

Notice in lines 14-16, I declared my variables, giving them a name. You can name your variables anything you want, with a rule of thumb as naming them something meaningful to your code (i.e avoid giving your variables arbitrary names like “x” or “y”). In line 29 the actual math process is taking place, storing the sum of “num1” and “num2” in a variable called “sum.” I also initialized my variables to zero. You should always initialize your variables.

I obtained data from the user by using the Scanner Class.

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

javac Add.java

*** To run the compiled program, simply type this command:

java Add

The above code should give you the following output:

Please enter the first number: 8
Please enter the second number: 24
The sum of 8 and 24 is: 32

==== SUBTRACTING TWO NUMBERS ====

Subtracting two ints works the same way as the above code, and we would only need to edit the above code in one place to achieve that. In line 29, replace the addition symbol with a subtraction sign, and you should have something like this

Note: In the above example, “cin.nextDouble()” was used on line 26 in place of “nextInt.” The declaration “nextDouble” can be used in place of “nextInt” in case you want to obtain floating point data from the user.

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

javac Subtract.java

*** To run the compiled program, simply type this command:

java Subtract

The above code should give you the following output

Please enter the first number: 8
Please enter the second number: 23.99999
The difference between 8 and 23.99999 is: -15.99999

==== MULTIPLYING TWO NUMBERS ====

This can be achieved the same way as the 2 previous methods, simply by editing line 29, and replacing the designated math operator with the star symbol “*”.

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

javac Multiply.java

*** To run the compiled program, simply type this command:

java Multiply

The above code should give you the following output

Please enter the first number: 7.999999
Please enter the second number: 24
The product of 7.999999 and 24 is: 191.99997


==== DIVIDING TWO NUMBERS TOGETHER ====

In division, when you divide numbers together, sometimes they end in decimals. Int data types can not store decimal data (try it yourself and see), so here is where the use of the double data type is mandatory.

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

javac Divide.java

*** To run the compiled program, simply type this command:

java Divide

The above code should give the following output

Please enter the first number: 7.99999
Please enter the second number: 23.99999
The quotient of 7.99999 and 23.99999 is: 0.33333305

==== MODULUS ====

If you wanted to capture the remainder of the quotient you calculated from the above code, you would use the modulus operator (%).

From the above code, you would only need to edit line 29, from division, to modulus.