In this lab you'll gain experience with Files, random numbers, and methods. What you learn in this lab should be helpful

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

In this lab you'll gain experience with Files, random numbers, and methods. What you learn in this lab should be helpful

Post by answerhappygod »

In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 1
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 1 (80.85 KiB) Viewed 23 times
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 2
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 2 (67.37 KiB) Viewed 23 times
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 3
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 3 (63.3 KiB) Viewed 23 times
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 4
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 4 (66.19 KiB) Viewed 23 times
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 5
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 5 (60.55 KiB) Viewed 23 times
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 6
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 6 (55.01 KiB) Viewed 23 times
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 7
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 7 (63.41 KiB) Viewed 23 times
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 8
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 8 (45.94 KiB) Viewed 23 times
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 9
In This Lab You Ll Gain Experience With Files Random Numbers And Methods What You Learn In This Lab Should Be Helpful 9 (63.29 KiB) Viewed 23 times
import java.util.Scanner; // Import the Scanner classimport java.io.*; // Import Java I/O classes// Define a new classpublic class ReadFileLineByLine {// the main methodpublic static void main (String[] args) throws IOException{// Important: make sure that you have retrieved the file// ReadFileLineByLine.txt from the Canvas' File->labs->lab6, and that// you have saved that file into your lab6 folder.// 1. declare a variable, myFileName, of type String, and assign// it the value ReadFileLineByLine.txt// 2. declare a variable, myFile, of type File, and// assign it to be a new instance of the File class,// and give the File class constructor the variable// myFileName as the single argument// 3. declare a variable, inputFile, of type Scanner,// and assign it to be a new instance of the Scanner// class, and give the Scanner class constructor// the variable myFile as the single argument// 4. declare a variable, loopNumber, of type int, and// assign it the value 0// 5. use a while loop, whose conditional is the following://// inputFile.hasNext()//// At each iteration of the while loop://// a. increment loopNumber by 1// b. declare variable fileLine as a String, and// assign it the value inputFile.nextLine();// c. write an if statement, that checks if// loopNumber modulus 7 is equal to zero; if it is// then use System.out.println to print to the// screen the value stored in fileLine// 6. close the file}}
In this lab you'll gain experience with Files, random numbers, and methods. What you learn in this lab should be helpful in completing homework #4, and in completing the final project (which requires the use of at least one File). Please submit your solutions to this lab to Canvas. Part I-Reading Lines from a File, line-by-line Up to this point, you've learned in class about the modulus operator, running totals, as well as Java's file I/O capabilities. In the program that you will write, you will use all of these, to read a file line-by-line, and to output to the screen only certain portions of that file. The entire pseudocode of the program is given to in the file ReadFi leLineByLine. Java, that you can download from Canvas at Files->labs-lab6. To complete this part of the lab: 1. Download the file ReadFileLineByLine.java from the course Canvas at Files->labs->lab6, and save it to your computer. 2. Compile and run the java file. Because at this point the main method of your program contains just comments, your program will not perform any sort of task. - Notice import java. util. Scanner; and import java. 10.∗; at the top of the java file. As was mentioned in lecture, these important Java import statements provide functionality for reading input from the keyboard and reading from a file. - Notice the throws IOException at the end of the main method declaration. As was discussed in lecture, this part of the code is required, if you are using Java's IOO capabilities. 3. Retrieve the MisteryFile.txt file from the schedule page of the course website and save that file to your computer to the same location where you saved ReadFileLineByLine.java. Open the file and inspect it. Can you make out any details? 4. Follow the instructions in the pseudocode in the ReadFileLineByLine.java file: - Declare a variable, myEileName, of type String, and assign it the value MisteryFile. txt. Remember that Strings are enclosed by double quotes. - Declare a variable, myFile, of type File, and assign it to be a new instance of the File class. Recall from lecture that to declare a new instance of a Class of type File, that references a specific filename, you would write:  File file = new File (myFileName);  - Declare a variable, inputEile, of type Scanner, and assign it to be a new instance of the Scanner class. Give the Scanner class constructor the variable myFile as the single argument. As you've already
done before several times, use the following template: Scanner inputFile = new Scanner (fi1e); - Declare a variable, 100pNum, of type int, and assign it the value 0 - Use a while loop, whose conditional is the following: input 1 le. hasNext (). This while loop will iterate through its body as long as the reference to input Fi le is not yet pointing to the end of the file. At each iteration of the while loop: a. Increment bopNum by 1 b. Declare variable fileline as a String, and assign it the value inputFile . nextline() c. Write an if statement, that checks if foopum modulus 7 is equal to zero; if it is then use System. Out. println to print to the screen the value stored in filetine. - Close the file by issuing inputEile + close(); 5. Compile and run your program. The output should print to the screen, every 7th line of the file, and the ASCII image should be something that you can easily recognize. II. Generating Random Numbers As was shown in lecture, Java's Random class can be used to generate random numbers. In this part of the lab. you'll write a java program, that will prompt the user to input how many lottery numbers should be guessed. A few sample invocations of the program are shown in Figure 1. Figure 1: Sample invocations of GenerateSometandomLot teryNums yava To complete this programming task: 1. Create a new file in jGRASP. Call it GenerateSomeRandomLotfery:Vums java, and save it. 2. The program uses the Scanner and Random classes, so you must import them at the top of the file: import java. uti1. Scanner; import java. ut 1. Random? 3. Write a main method, that prints to the screen the following instructions (use a combination of p≤1nt1n
and print statements, as necessary): I know:you are busy, so I will guesn your lottery numbers for you! How many numbers should 1 quess? 4. Set up a Scanner object; tell it to listen to the keyboard, by writng Systeni. in in the constructor. 5. Declare a variable of type int, and use the next int () method of Scanner, to retrieve from the user, and save into the variable, an integer value. 6. Make your program print to the screen, the following message: What is the highest possable lottery number? 7. Again use the next Int () method of the Scanner object (you don't have to recreate a scanner object: just use the one that you created in the previous steps). Save the user's input into a new variable of type int, which will hold the maximum possible random number that should be generated. Be sure to use a good, descriptive variable name, such as highest Poss ibleLotteryNum. 8. In order to generate a random number, you must create the Random class in java, as was shown in lecture. To do this, you'd write: Random randomNumbers = new Random (); 9. Write a for loop, that will iterate from 0 through the value of the variable that holds the maximum possible random number that you want your program to generate. for (int i =0;i< numLotteryNums; 1++) 10. Inside the body of your for loop: - Create a new variable of type integer, and call it randomNum - To generate a random number between zero and some upper-limit, use the next Int () method of the Random class. Recall from lecture, that there are several forms of the nextint method in the Random class. If you invoke the method without any arguments, then a random number in the range 2,147,483,648 to +2,147,483,648 will be generated. If you pass a single integer argument with value n. then a random number in the range 0 through n will be generated. For your purposes, generate a random number that is in the range of 0 through the value stored in highestPossibleLotteryNum - Write an if, else-if, else statement, that will output to the screen the lottery number that is created at each iteration of the for loop. Make sure that the output states whether the random number is the first, next, or last lottery number. You can determine this by looking at the iterator of your for loop. 11. Compile and run your program, and make sure that you get similar output that is shown in Figure 1 .
III. Writing a Program with Methods For this part of the lab, a java program file without methods is provided for you on the schedule page of the course website. The program reads two integers from the keyboard, and outputs a third integer, which is the first integer raised to the power indicated by the second integer. For example, if the first integer is 3 , and the second integer is 4 , then the program calculates and outputs 34=3×3×3×3=81. Two sample runs of the program are shown in Figure 2. To get started, download and save to your computer, the file My.Program WithoutMethods.java. Compile and run the program (Also shown in Figure 3 ). \begin{tabular}{l} This program calculates the nth power of a base integer input by the user. \\ Please input your base; an integer less than 10:5 \\ Please input your exponent; a positive integer less than 10:7 \\ The integer 5 raised to the 7 th power: 78125 \\ \hline This program calculates the nth power of a base integer input by the user. \\ Please input your base; an integer less than 10:3 \\ Please input your exponent; a positive integer less than 10:3 \\ The integer 3 raised to the 3th power: 27 \\ \hline Figure 2: Two sample nuns of the program My Programwi thoutMethods. java \\ \hline \end{tabular} At this point, you have a fully functioning java program. However, as mentioned in class, the program's main method is a bit cluttered, and it is not easy to read. In the subsequent steps you'll modify your program by writing several methods. This will "un" clutter the main method.
IIIa. Adding a printInstructions() Method The goal of this step is to simplify the main routine. To do that, you'll write a method that achieves the same functionality that is shown in lines 10-11 of your MyProgramWi thout eethods. Java program in Figure 3. Recall from lecture that the simplest type of method is one that does not return a value, nor receives a parameter. In class, we defined and used the following displayInstructions () method: In this step of the lab, you'll write your own displayinstructions method. To do so: 1. Create a new java file. Cut and paste the code from your MyProgram WithoutMethods java into the new just-created new java file. 2. Change the class name in the new java file to MyProgramWithOneMethod, and save the java file as MyProgramWithOneMethod.java 3. In order to create a new method, you have to write the correct method's header, and body (refer to the slides from lecture if you need to review). Write a new method, that retums void, receives zero parameters, and is called printinstructions. The header of the method is the following, which should be written in your java file, above the main method: public static void printinstructions () 4. The body of this new printinstructions method should contain a single print in statement: System.out.println("zhis progran calculates the nth power of a base " + "integer input by the urer."); 5. Edit the main routine so that instead of: System.out, println ("This progrant calculates the nth power of a base "+ "integer input by the user."); you invoke the printInstructions method: printinstructions (); Recall from lecture that when invoking a method, you do NOT write the method modifiers that are part of the method's header; you also do not write the method's return type. You JUST write the method's name, and any input parameters, in parentheses, if the method requires parameters. In this first case, printinstructions () does not require any input parameters.
Compile and run your program. It should behave exactly as the first program. Except this time, the instructions are printed by the printinstructions method invoked from within the main method. Your code of your MyProgram WhhoneMethod.java file should look similar to Figure 4. Figure 4: The class MyProgramWithOneMethod, with the method printinstruetions()
IIIb. Adding a getintegerFromKeyboard0 Method In this section, you will write a method that instantiates the Scanner class, receives input from the user, and then returns the integer that was input via the keyboard. In lecture, we wrote the following method: In this step of the lab, you'll add a get integerFromKeyboard method to your program, and you'll call that method twice, once to retrieve the base integer, and the second time to retrieve the exponent integer. The lesson here is that you can reuse a method as many times as needed. To complete this step: 1. Create a new java file and cut and paste the code from your MyProgramHithOneMethod,java into the just-created new java file. 2. Change the class name in the new java file to MyProgramWithTwoMethods, and save the file as MyProgramHithTwoMethods.java 3. Write a new method, that receives zero parameters, reads an integer input from the keyboard, and returns that value of type integer. Name your method get Integer Fromkeyboard. The method's header, and body, should be the following: System. out.println("please L mput youz base; an integer lesa than 10 : "l : Be sure to remove the statement Scanner keyboard = new Scanner (System. in); from your main method. Notice how you are using the get integerFromKeyboard method twice. 5. Compile and debug your program, and make sure that it performs the same way as your previous two

IIIc. Adding the calcExponentValue Method to your program In this final section, you'll write a method that takes two arguments - both of them integers - and calculates the value of raising the first integer to the power indicated by the second integer. For example, if the first integer provided by the user is 3 , and the second integer provided by the user is 4 , then the method would calculate 34=3×3×3×3=81. To complete this step: 1. Create a new java file. Cut and paste the code from your MyProgramNithouttwoMethods. Java into the just-created new java file. 2. Change the class name in the new java file to MyProgramWithThreeMethods, and save the file as My ProgramWithThteeMethods. java 3. Write the following method: Af a method that takes two argumenta, and calculates the fizet input. /1 argument rained to the powet of the mecond argument public statie int caleExponentValue(int integervalue, int exponentValue) ( Int integerpower = integervalue; for (1nt 1=2;1<= exponentvalue; 1++)1 integerpower * = integervalue: 1 return integerporier; Notice that the method calcExponentValue takes two arguments, the first an integer, and the second also an integer. When you invoke the method from the main routine of your program, you have to pass the values in the correct order. 4. Invoke the calcExponentVal ue method in the main part of your program. 5. The final, main routine is the following, where the calcExponentValue method is called directly within the System. out. println statement. 6. After you've added the calcExponentValue method into your class, and after you've invoked that method in your main method, compile and run your program, which should look similar to Figure 6 . Test it on a few sample inputs. If it works as expected, then you are done. Notice how the main method, which now includes invocations of several other methods, is much easier to read than the original main method of the MyProgramWs thoutMethods class.
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply