Monthly Archives: June 2012

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) setwL - Right justifies string data of size "width," filling the width to the left of the string with whitespace.

(2) setwR - Left justifies string data of size "width," filling the width to the right of the string with whitespace.

== SETW/SETFILL ==

(3) setwLF - Right justifies string data of size "width," filling the width to the left of the string with a custom filler character.

(4) setwRF - Left justifies string data of size "width," filling the width to the right of the string with a custom 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!