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 (64.83 KiB) Viewed 14 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 (65.81 KiB) Viewed 14 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 (64.78 KiB) Viewed 14 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 (63.66 KiB) Viewed 14 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 (61.75 KiB) Viewed 14 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 (65.27 KiB) Viewed 14 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 (64.54 KiB) Viewed 14 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 (74.62 KiB) Viewed 14 times
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 peoject (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, tine-by-line Up to this point, you've leamed in class aboat the modulus operator, running totals, as well as favais file lO capabilities. In the program that you will write, you will use all of these, to read a file line-by-liae, and to output, to the screen only certain portions of that file. The entire pseudocode of the program is given to in the file ReadFileLineByL1ne. Java, that you can download from Canvas at Fles-labs-lab6. To complete this part of the lab: 1. Download the file ReadFileLineByLine java from the course Canvas at Files- → labs-slab6, and save it to your computer. 2. Compile and run the java fille. 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 . uti1. Scanner; and import java.10.* z at the top of the java file. As was mentioned in lecture, these important Java import statements peovide functioeality for reading input . from the keyboard and reading from a file. - Notice the throws 1OException 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 10 capabilities. 3. Retrieve the Mistery File sul file from the schedule page of the coune website and ave that file to your computer to the same location where you saved ReadFile LineBy Line jond. 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, myEileNane, of type String, and assign it the value MisteryFile. txte. Remember that Strings are enclosed by double quotes. - Declare a variable, myFile, of type File, and assign it to be a new insunce 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 (myFiletame); - Declare a variable, inpueFile, of type Scanner, and assign it to be a new instance of the 5 canner class. Give the Scanner class constructor the variable myF1le as the single argoment. As you've already
- Use a while loop, whose conditional is the following: input File. hasNext (). This while loop will iterate through its body as long as the reference to inputF 11 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 fil eline as a String, and assign it the value inputFite. nextLine() c. Write an if statement, that checks if loopNum modulus 7 is equal to zero, if it is then use System. out. println to print to the screen the value stored in fileline. - Close the file by issuing inputFile . elose(); 5. Compile and run your program. The outpot should print to the screen, every 7th line of the file, and the ASCII image should be something that you can easily rocognize. 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 lostery numbers shoold be guessed. A. few sample invocations of the program are shown in Figure 1. Figure 1: Sample invocations of GeneratesomeRandomLottery1vumsyava Tosomplete this programming task: 1. Create a new file in jGRASP. Call it GenerateSomeRandomLontery Nums jova, 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.utiliscanner; import: java, ut:1. Randomi 3. Wrie a main method, that prints to the screen the following instructions (use a combination of print1n
and print statements, as necessary): I know you are busy. so I will guess your lottery numbers for you? How many numbers should I quess? 4. Set up a Scanner object; tell it to listen to the keyboard, by writng System o 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 posstble lottery number? 7. Again use the nextint () 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 highestpossibleLotteryNum. 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=0i​1< numLotteryNums i1++) 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 rero and some upper-limit, use the nextint () method of the Random class. Recall from lecture, that there are several forms of the next Int 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-1f, else statement, that will outpat to the sereen the lotiery 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 MyProgramWithoutMethods, java. Compile and run the program (Also shown in Figure 3). At this point, you have a fully functioning java program. However, as mentioned in class, the programis main method is a bit cluttered, and it is not easy to read. In the subsequent steps you'l modify your program by writing several methods. This will "un" clufter the main method.
IIIa. Adding a printInstructions 0 Method The goal of this step is to simplify the main routine. To do that, youll write a method that achieves the same functionality that is shown in lines 10-11 of your MyProgramwithoutMechods - 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: If a nethod that prints instructions public static void displayinstructions () . System, out. println("Hello, this prograe pertoras *" + "a sinple calculation"); In this step of the lab, you'll write your own displayinstruct fons method. To do so: 1. Create a new java file. Cut and pase the code from your MyProgram WathoutMethodr,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 it MyProgramWithOneMethod java 3. In order to create a new method, you have to write the correct method's beader, and body (refer to the slides from lecture if you need to review). Write a new method, that returns void, receives zero parameters, and is called print Instruet ions. The header of the method is the following. which should be written in your java file, above the main method: public statie void printinstruetions () 4. The body of this new print Instruetions method should contain a single printin statement: System, out.println (*2his program calculates the nth pover of a base * + "integer input by the aate") a 5. Edit the main routine so that instead of: System,out, println ("Thin progran calculates the nth pover of a base " + "integer inpat by the anet." J you invoke the printinstructions method: - printinstructions (1) Recall from lecture that when invoking a method, you do NOT write the method modifiers that are part of the method's beader; you also do not write the method's return type. You JUST write the method's name, and any input parameters, in parcntheses, if the method requires parametern. In this first case, printinstruetions () does not require any inpot parameten.
6. Comipile 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 WithOneMethod yava file should look similar to Figure 4. Figure 4: The class MyProgramwithOneMethod, with the method printInstructions ()
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: 1f a nethod that sueries a user for a number f/ and returns the value nupplied via the kepbost public static int getusersinput ( ) Systen, aut.printlnf " Flease input an integer- " 1 ; Sconner keyboard a new Scanner(5ystea. in i: Int userinput = keybeard , nextint (\}: In this step of the lab, you'll add a get. Integer FromKeyboard method to your program, and you'll call that method twice, once to retrieve the base integer, and the second time to retrieve the expe here is that you can reuse a method as many times as needed. To complete this step: here is that you can reuse a method as many times as needed. To complete this step: 1. Create a new java fille and cut and paste the code from your MyProgramWithOneMethod juva into the just-created new java file. 2. Change the class name in the new java file to MyProgramWithTwoMethods, and save the file as MyProgramWithTwoMethods 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 FromFeyboard. The methods header, and body, should be the following: /f a mothod that inatantiates a Scanner class, 1asterna to the keytoard. ff retrieves an integer, and returna the value public static int getintegerFromkeyboard () I Scaniner keyboard - new Scanner (System in) z int keyboardtnput - keyboard, nextint () I return keyboardinputz 4. Modify the main method of your program, so that it retrieves the input from the keyboard, using the getintegerpromkeyboard method: Be sure to remove the statement scanner keyboard = new Scanner (Syatem.{n) i 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 perfocms the same way as your previous two programs in this part of the lab. Your program should look similar to what is shown in Figure
IIIc. Adding the calcExponent Value Method to your program In this final'section, you'l 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 My ProgramwithoutTwoMethods. 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 MyProgramhi th ThreeMethods. Java 3. Write the following method: 11. a method that takes two arquments, and calculates the tirst input 1/ argument ralsed to the power of the second argument public atatic int calczxponentValue (int integerValue, int exponentValue) if Int integerpower - integerValue; for (int 1−2,1<− exponentvalue; 1++1 t integerpower * integervalue; return integerpower; 1. Notice that the method caleExponentValue takes two arguments, the first an iateger, 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 caloExponentValue method in the main part of your program. 5. The final, main routine is the following, where the caleExponentValue method is called directly within the System, out. printin statement. 6. After you've added the caleExponentValue 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 MyProgramNithoutMethods 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