Monthly Archives: November 2012
Java || Snippet – How To Read & Write Data From A File
This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program will read in data from a file (numbers), manipulate that data, and output new data into a different text file.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
Try/Catch - What Is It?
The "Math" Class - sqrt and pow
The "Scanner" Class - Used for the input file
The "FileWriter" Class - Used for the output file
The "File" Class - Used to locate the input/output files
Working With Files
NOTE: The data file that is used in this example can be downloaded here.
In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .java file is saved in. If you are using Eclipse, the default directory will probably be:
Documents > Workspace > [Your project name]
Alternatively, you can execute this command, which will give you the current directory in which your source file resides:
System.out.println(System.getProperty("user.dir"));
Whatever the case, in order to read in the data .txt file, your program must know where it is located on the system.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
import java.io.File; // used to locate the input/output files import java.io.FileWriter; // used for file output import java.util.Scanner; // used for file input public class ReadWriteFile { public static void main(String[] args) { // declare & initialize variables Scanner infile; FileWriter outfile; double a=0,b=0,c=0; double root1=0, root2=0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // use a try/catch to check to see if the input file exists, & if not then EXIT try { // this opens the input file // YOUR INPUT FILE NAME GOES BELOW infile = new Scanner(new File("INPUT_Quadratic_programmingnotes_freeweq_com.txt")); // this opens the output file // if the file doesnt already exist, it will be created outfile = new FileWriter(new File("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt")); // if the file was found, this try/catch will execute, and the loop will // attempt to get the 3 numbers from the input file and place // them inside the variables 'a,b,c' try { while(infile.hasNext()) { // this assigns the incoming data to the // variables 'a', 'b' and 'c' // NOTE: it is just like a normal scanner statement a = infile.nextInt(); b = infile.nextInt(); c = infile.nextInt(); // NOTE: if you want to read in data into an array // your declaration would be like this // ------------------------------------ // a[counter] = infile.nextInt(); // b[counter] = infile.nextInt(); // c[counter] = infile.nextInt(); // ++counter; } } catch(Exception e) { // if there was an error on input, (i.e the input file contains letters) // this block will execite, and the program will exit System.err.println("There is a formatting error in the input file!n" + "The input file should contain only 3 numbersn"); System.exit(1); } // this does the quadratic formula calculations root1 = ((-b) + Math.sqrt(Math.pow(b,2) - (4*a*c)))/(2*a); root2 = ((-b) - Math.sqrt(Math.pow(b,2) - (4*a*c)))/(2*a); // this displays the numbers to screen via stdout System.out.println("For the numbers:na = "+a+"nb = "+b+"nc = "+c); System.out.println("nroot 1 = "+root1+"nroot 2 = "+root2); // this saves the data to the output file // NOTE: its almost exactly the same as the above print statement, except // the 'write' function is dependent on the "newline" (NL) method // to generate a line break String NL = System.getProperty("line.separator"); outfile.write("For the numbers:"+NL+"a = "+a+NL+"b = "+b+NL+"c = "+c); outfile.write(NL+NL+"root 1 = "+root1+NL+"root 2 = "+root2); // close the input/output files once you are done using them infile.close(); outfile.close(); } catch(Exception e) { // if the file cannot be found, this block will execute, and the // program will exit System.err.println("Error, the input file could not be found!n" +e.getMessage()); System.exit(1); } System.out.println("nProgram Success!!n"); }// end of main }// http://programmingnotes.org/ |
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
(Remember to include the example input file)
Welcome to My Programming Notes' Java Program.
For the numbers:
a = 2.0
b = 4.0
c = -16.0root 1 = 2.0
root 2 = -4.0Program Success!!
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
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import java.util.Random; public class HighestLowestArray { // global variable declaration final static int ARRAY_SIZE = 14; // const int allocating space for the array static Random rand = new Random(); // this is the call to the "Random" class public static void main(String[] args) { // declare & initialize variables int[] arry = new int[ARRAY_SIZE]; int highestScore = -999999; int lowestScore = 999999; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < ARRAY_SIZE; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Output the original array values for(int x = 0; x < ARRAY_SIZE; ++x) { System.out.print(arry[x]+" "); } System.out.println(""); // creates a line seperator setwLF("",60,'-'); // use a for loop to go thru the array checking to see the highest/lowest element System.out.print("nThese are the highest and lowest array values: "); for(int index=0; index < ARRAY_SIZE; ++index) { // if current score in the array is bigger than the current 'highestScore' // element, then set 'highestScore' equal to the current array element if(arry[index] > highestScore) { highestScore = arry[index]; } // if current 'lowestScore' element is bigger than the current array element, // then set 'lowestScore' equal to the current array element if(arry[index] < lowestScore) { lowestScore = arry[index]; } }// end for loop // display the results to the user System.out.print("nHighest: "+highestScore); System.out.print("nLowest: "+lowestScore); System.out.println(""); }// end of main static public void setwLF(String str, int width, char fill) { for (int x = str.length(); x < width; ++x) { System.out.print(fill); } System.out.print(str); }// end of setwLF }// http://programmingnotes.org/ |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.util.Scanner; public class ArrayInput { // global variable declaration static Scanner cin = new Scanner(System.in); final static int ARRAY_SIZE = 100; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int numElems = 0; int[] myArray = new int[ARRAY_SIZE]; // declare array which has the ability to hold 100 elements System.out.println("Welcome to My Programming Notes' Java Program.n"); // ask user how many items they want to place in array System.out.print("How many items do you want to place into the array?: "); numElems = cin.nextInt(); System.out.println(""); // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { System.out.print("Enter item #"+(index+1)+": "); myArray[index] = cin.nextInt(); } // display data to user System.out.print("nThe current items inside the array are: "); // display contents inside array using a for loop for(int index=0; index < numElems; ++index) { System.out.print("nItem #"+(index+1)+": "+myArray[index]); } System.out.println(""); }// end of main }// http://programmingnotes.org/ |
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: 2321The current items inside the array are:
Item #1: 12
Item #2: 43
Item #3: 5
Item #4: 643
Item #5: 2321
Java || Modulus – Celsius To Fahrenheit Conversion Displaying Degrees Divisible By 10 Using Modulus
This page will consist of two simple programs which demonstrate the use of the modulus operator (%).
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Modulus
Do/While Loop
Methods (A.K.A "Functions") - What Are They?
Simple Math - Divisibility
Celsius to Fahrenheit Conversion
===== FINDING THE DIVISIBILITY OF A NUMBER =====
Take a simple arithmetic problem: what’s left over when you divide an odd number by an even number? The answer may not be easy to compute, but we know that it will most likely result in an answer which has a decimal remainder. How would we determine the divisibility of a number in a programming language like Java? That’s where the modulus operator comes in handy.
To have divisibility means that when you divide the first number by another number, the quotient (answer) is a whole number (i.e – no decimal values). Unlike the division operator, the modulus operator (‘%’), has the ability to give us the remainder of a given mathematical operation that results from performing integer division.
To illustrate this, here is a simple program which prompts the user to enter a number. Once the user enters a number, they are asked to enter in a divisor for the previous number. Using modulus, the program will determine if the second number is divisible by the first number. If the modulus result returns 0, the two numbers are divisible. If the modulus result does not return 0, the two numbers are not divisible. The program will keep re-prompting the user to enter in a correct choice until a correct result is obtained.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import java.util.Scanner; public class Modulus { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare & initialize variables int numerator = 0; int denominator = 0; double multiple = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // get first number System.out.print("Please enter a value: "); numerator = cin.nextInt(); // get second number System.out.print("nPlease enter a factor of "+numerator+": "); do{ // loop will keep going until the user enters a correct answer denominator = cin.nextInt(); // this is the modulus declaration, which will find the // remainder between the 2 numbers multiple = numerator % denominator; // if the modulus result returns 0, the 2 numbers // are divisible if(multiple == 0) { System.out.println("nCorrect! "+numerator+" is divisible by " +denominator); System.out.println("n("+numerator+"/"+denominator+") = " + ""+(numerator/denominator)); } // if the user entered an incorrect choice, promt an error message else { System.out.print("nIncorrect, "+numerator+" is not divisible by " +denominator); System.out.print(".nnPlease enter a new multiple integer for " +numerator+": "); } }while(multiple != 0); // ^ loop stops once user enters correct choice }// end of main }// http://programmingnotes.org/ |
The above program determines if number ‘A’ is divisible be number ‘B’ via modulus. Unlike the division operator, which does not return the remainder of a number, the modulus operator does, thus we are able to find divisibility between two numbers.
To demonstrate the above code, here is a sample run:
Welcome to My Programming Notes' Java Program.
Please enter a value: 21
Please enter a factor of 21: 5Incorrect, 21 is not divisible by 5.
Please enter a new multiple integer for 21: 7
Correct! 21 is divisible by 7(21/7) = 3
===== CELSIUS TO FAHRENHEIT CONVERSION DISPLAYING DEGREES DIVISIBLE BY 10 =====
Now that we understand how modulus works, the second program shouldn’t be too difficult. This function first prompts the user to enter in an initial (low) value. After the program obtains the low value from the user, the program will ask for another (high) value. After it obtains the needed information, it displays all the degrees, from the range of the low number to the high number, which are divisible by 10. So if the user enters a low value of 3 and a high value of 303, the program will display all of the Celsius to Fahrenheit degrees within that range which are divisible by 10.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import java.util.Scanner; public class Temperature { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare & initialize variables int low = 0; int high = 0; double degreeFahrenhiet = 0; double multiple = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // get data from user System.out.print("Enter a low number: "); low = cin.nextInt(); System.out.print("nEnter a high number: "); high = cin.nextInt(); // displays data back to user in table form System.out.print("nCelsius Fahrenheit:n"); // display the initial 'low' converted degrees to the user System.out.println(low+"t"+ConvertCelsiusToFahrenheit(low)); // this loop displays all the degrees that are divisible by 10 do{ // this increments the current degree number by 1 ++low; // this converts the current number from celsius to fahrenhiet degreeFahrenhiet = ConvertCelsiusToFahrenheit(low); // this is the modulus operation which finds the // numbers which are divisible by 10 multiple = low % 10; // the program will only display the degrees to the user via // cout which are divisible by 10 if(multiple == 0) { System.out.println(low+"t"+degreeFahrenhiet); } }while(low < high); // ^ loop stops once the 'low' variable reaches the 'high' variable // displays the 'high' converted degrees to the user System.out.println(high+"t"+ConvertCelsiusToFahrenheit(high)); }// end of main static double ConvertCelsiusToFahrenheit(int degree) { return ((1.8 * degree) + 32.0); }// end of ConvertCelsiusToFahrenheit }// http://programmingnotes.org/ |
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 low number: 3
Enter a high number: 303Celsius Fahrenheit:
3..........37.4
10.........50
20.........68
30.........86
40........104
50........122
60........140
70........158
80........176
90........194
100.......212
110.......230
120.......248
130.......266
140.......284
150.......302
160.......320
170.......338
180.......356
190.......374
200.......392
210.......410
220.......428
230.......446
240.......464
250.......482
260.......500
270.......518
280.......536
290.......554
300.......572
303.......577.4
Java || Random Number Guessing Game Using Random & Do/While Loop
This is a simple guessing game, which demonstrates the use of the “Random” class to generate random numbers. This program first prompts the user to enter a number between 1 and 1000. Using if/else statements, the program will check to see if the user obtained number is higher/lower than the pre defined random number which is generated by the program. If the user makes a wrong guess, the program will re prompt the user to enter in a new number, where they will have a chance to enter in a new guess. Once the user finally guesses the correct answer, using a do/while loop, the program will ask if they want to play again. If the user selects yes, the game will start over, and a new random number will be generated. If the user selects no, the game will end.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
The "Random" Class
Do/While Loop
How To get Character Input
Custom Setw/Setfill In Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
// ============================================================================ // Author: Kenneth Perkins // Date: Nov 19, 2012 // Taken From: http://programmingnotes.org/ // File: GuessingGame.java // Description: Demonstrates a simple random number guessing game // ============================================================================ import java.util.*; public class GuessingGame { // global variable declarations static Scanner cin = new Scanner(System.in); static Random rand = new Random(); // this is the call to the "Random" class public static void main(String[] args) { // declare & initialize variables char playAgain = 'y'; int userInput = 0; int numGuesses = 0; int randomNumber = rand.nextInt(1000)+1; // ^ get a number from the random generator in the range of 1 - 1000 System.out.println("Welcome to My Programming Notes' Java Program.\n"); // display directions to user System.out.println("I'm thinking of a number between 1 and 1000. Go " + "ahead and make your first guess.\n"); do { // this is the start of the do/while loop System.out.print(">> "); // get data from user userInput = cin.nextInt(); System.out.println(""); // increments the 'numGuesses' variable each time the user // gets the guess wrong ++numGuesses; // if user guess is too high, do this code if (userInput > randomNumber) { System.out.println("Too high! Think lower."); } // if user guess is too low, do this code else if (userInput < randomNumber) { System.out.println("Too low! Think higher."); } // if user guess is correct, do this code else { // display data to user, prompt if user wants to play again System.out.print("You got it, and it only took you " +numGuesses+" trys!\nWould you like to play again (y/n)? "); playAgain = cin.next().charAt(0); // if user wants to play again then re initialize the variables if (playAgain == 'y'|| playAgain == 'Y') { // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 60, '-'); numGuesses = 0; System.out.println("\n\nMake a guess (between 1-1000):\n"); // generate a new random number for the user to try & guess randomNumber = rand.nextInt(1000)+1; } } System.out.println(""); } while (playAgain == 'y' || playAgain == 'Y'); // ^ do/while loop ends when user doesnt select 'Y' // display data to user System.out.println("Thanks for playing!!"); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ |
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.
I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.
>> 900
Too high! Think lower.
>> 300
Too high! Think lower.
>> 100
Too low! Think higher.
>> 200
Too low! Think higher.
>> 350
You got it, and it only took you 5 trys!
Would you like to play again (y/n)? y------------------------------------------------------------
Make a guess (between 1-1000):
>> 300
Too low! Think higher.
>> 600
Too high! Think lower.
>> 500
Too high! Think lower.
>> 400
You got it, and it only took you 4 trys!
Would you like to play again (y/n)? nThanks for playing!!