CS 110, Programming Fundamentals I Lab 6: Files and methods Upload to Canvas In this lab...
Fantastic news! We've Found the answer you've been seeking!
Question:
Transcribed Image Text:
CS 110, Programming Fundamentals I Lab 6: Files and methods Upload to Canvas 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 ReadFileLineByLine.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. 3. 4. . CWU Computer Science . 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.io.*; 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 I/O capabilities. 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? Follow the instructions in the pseudocode in the ReadFileLineByLine.java file: Declare a variable, myFileName, 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); Page 1 of 12 ZOOM + Upload to Canvas 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 ReadFileLineByLine.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. Computer Science 3. 4. 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.io.*; 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 I/O capabilities. 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? Follow the instructions in the pseudocode in the ReadFileLineByLine.java file: . Declare a variable, myFileName, 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, input File, 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 CS110, Tatiana Harrison, CWU, Lab 6: processing Files and Writing MethodsPage 1 of 12 Page 1 of 12 ZOOM + . done before several times, use the following template: Scanner inputFile = new Scanner (file); Increment loop Num by 1 Declare variable fileLine as a String, and assign it the value inputFile.nextLine() 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 input File.close(); 5. Compile and run your program. The output should print to the screen, every 7th ASCII image should be something that you can easily recognize. II. Generating Random Numbers Declare a variable, loop Num, of type int, and assign it the value 0 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 inputFile is not yet pointing to the end of the file. At each iteration of the while loop: 2. a. 3. b. C. 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. I know you are busy, so I will guess your lottery numbers for you! How many numbers should I guess? 3 What is the highest possible lottery number? 98 The first lottery Number is: 63 The next lottery Number is: 82 The last lottery Number is: 79 Good luck! User indicates 3 numbers, no greater than 98 I know you are busy, so I will guess your lottery numbers for you! How many numbers should I guess? 7 What is the highest possible lottery number? 7845 The first lottery Number is: 7175 The next lottery Number is: 2272 The next lottery Number is: 6106 The next lottery Number is: 903 The next lottery Number is: 3291 The next lottery Number is: 328 The last lottery Number is: 182 Good luck! file, and the I know you are busy, so I will guess your lottery numbers for you! How many numbers should I guess? 5 What is the highest possible lottery number? 7634543 User indicates 7 numbers, no greater than 7845 Figure 1: Sample invocations of GenerateSome RandomLotteryNums java The first lottery Number is: 7590308 The next lottery Number is: 4283235 The next lottery Number is: 4609907 The next lottery Number is: 6447816 The last lottery Number is: 560108 Good luck! To complete this programming task: 1. Create new file in jGRASP. Call it GenerateSomeRandomLotteryNums.java, and save it. The program uses the Scanner and Random classes, so you must import them at the top of the file: import java.util.Scanner; import java.util.Random; Write a main method, that prints to the screen the following instructions (use a combination of println User indicates 5 numbers, no greater than 7634543 Page < 2 of 12 ZOOM + 4. 5. 6. 7. 8. 9. 10. 11. and print statements, as necessary): I know you are busy, so I will guess your lottery numbers for you! How many numbers should I guess? Set up a Scanner object; tell it to listen to the keyboard, by writng System. in in the constructor. Declare a variable of type int, and use the nextInt () method of Scanner, to retrieve from the user. and save into the variable, an integer value. Make your program print to the screen, the following message: What is the highest possible lottery number? 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 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 possibleLotteryNum. 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 (); 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; i++) 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 highest PossibleLotteryNum 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. Compile and run your program, and make sure that you get similar output that is shown in Figure 1. CS110, Tatiana Harrison, CWU, Lab 6: processing Files and Writing MethodsPage 3 of 12 Page < 3 of 12 ZOOM + 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 x 3 x 3 x 3 = 81. Two sample runs of the program are shown in Figure 2. To get started, download and save to your computer, the file MyProgram Without Methods.java. Compile and run the program (Also shown in Figure 3). 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 7th power: 78125 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 1 // import statements 2 import java.util.Scanner; 3 4 public class MyProgram Without Methods { 6 7 10 13 14 15 16 17 6227237ERNE 18 10 19 20 21 Figure 2: Two sample runs of the program MyProgramWithoutMethods.java // the main routine public static void main (String[] args) { 27 } 28} // print to the screen, instructions System.out.println("This program calculates the nth power of a base integer input by the user."); System.out.print("Please input your base; an integer less than 10 : "); // receive user's input Scanner keyboard = new Scanner(System.in); int myInteger = keyboard.nextInt(); System.out.print("Please input your exponent; a positive integer less than 10 : "); int myExponent keyboard.nextInt(); int myIntegerPower = myInteger; // perform calculation for (int i = 2; i 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 MyProgramwithoutMethods.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: 1 2. In this step of the lab, you'll write your own displayInstructions method. To do so: Create a new java file. Cut and paste the code from your MyProgram Without Methods.java into the new just-created new java file. 3. 4. // a method that prints instructions public static void display Instructions () { 5. } System.out.println("Hello, this program performs " "a simple calculation"); Change the class name in the new java file to MyProgram WithOne Method, and save the java file as MyProgram WithOneMethod.java 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 returns void, receives zero parameters, and is called print Instructions. The header of the method is the following, which should be written in your java file, above the main method: public static void printInstructions () The body of this new print Instructions method should contain a single println statement: System.out.println("This program calculates the nth power of a base " + "integer input by the user."); Edit the main routine so that instead of: System.out.println ("This program calculates the nth power of a base " + "integer input by the user."); you invoke the print Instructions method: print Instructions (); 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, print Instructions () does not require any input parameters. CS110, Tatiana Harrison, CWU, Lab 6: processing Files and Writing MethodsPage 5 of 12 Page < 5 of 12 ZOOM + 6. 1 // import statements. 2 import java.util.Scanner; 3 4 public class MyProgramWithOneMethod { 5 6 7 8 9 10 11 12 13 14 15 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 WithOneMethod.java file should look similar to Figure 4. 16 17 41 42 43 44} // a method to print instructions public static void print Instructions () { System.out.println("This program calculates the nth power "of a base integer input by the user."); } // a method to read an integer value from the keyboard public static int get IntegerFromKeyboard () { Scanner keyboard = new Scanner (System.in); int keyboardInput = keyboard.nextInt (); return keyboardInput; } // the main routine public static void main (String[] args) { } // print to the screen, instructions print Instructions(); // receive user's input Scanner keyboard = new Scanner(System.in); System.out.print("Please input your base; "an integer less than 10 "); int myInteger = keyboard.nextInt (); System.out.print("Please input your exponent; + "a positive integer less than 10 : "); int myExponent = keyboard.nextInt (); int myIntegerPower = myInteger; // perform calculation for (int i= 2; i IIIb. Adding a getIntegerFromKeyboard() 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: 1. 2. 3. In this step of the lab, you'll add a getInteger 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 exponent integer. The lesson here is that you can reuse a method as many times as needed. To complete this step: 4. 5. // a method that queries a user for a number // and returns the value supplied via the keyboard public static int getUsers Input () { } System.out.println("Please input an integer: "); Scanner keyboard=new Scanner (System.in); int userInput keyboard.nextInt (); System.out.println("You've supplied + userInput); return userInput; Create a new java file and cut and paste the code from your MyProgram WithOneMethod.java into the just-created new java file. } Change the class name in the new java file to MyProgram With TwoMethods, and save the file as MyProgram With TwoMethods.java 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: // a method that instantiates a Scanner class, listens to the keyboard, // retrieves an integer, and returns the value public static int getIntegerFromkeyboard () { Scanner keyboard= new Scanner (System.in); int keyboardInput = keyboard.nextInt (); return keyboardInput; Modify the main method of your program, so that it retrieves the input from the keyboard, using the getIntegerFromKeyboard method: // receive user's input System.out.println("Please input your base; an integer less than 10 : "); int my Integer = getIntegerFromkeyboard (); System.out.println("Please input your exponent; a positive" + "integer less than 10 "); int myExponent = getInteger Fromkeyboard (); int myIntegerPower = myInteger; Be sure to remove the statement Scanner keyboard = new Scanner (System.in); from your main method. Notice how you are using the get Integer FromKeyboard method twice. Compile and debug your program, and make sure that it performs 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 CS110, Tatiana Harrison, CWU, Lab 6: processing Files and Writing MethodsPage 8 of 12 Page < 8 of 12 ZOOM + The following files should be uploaded to Canvas (use the "Add Another File" option to submit multiple files, do not zip): ReadFileLineByLine.java GenerateSomeRandomLotteryNums.java MyProgram WithOneMethod.java MyProgram With TwoMethods.java MyProgram WithThree Methods.java V. Rubric File / task ReadFileLineByLine.java compiles and generates correct ASCII image Generate SomeRandomLotteryNums.java compiles and generates lottery numbers MyProgram WithOneMethod.java compiles and generates correct output MyProgram With Twos Methods.java compiles and generates correct output MyProgram With Three Methods.java compiles and generates correct output All java files are commented, and contain your name and date Variable names are adequate and descriptive in all java files, good code formatting Points 30 30 10 10 10 5 5 Total 100 Page < 12 of 12 ZOOM + import java.util.Scanner; import java.io. *; // Define a new class. public class Read FileLineByLine { } // Import the Scanner class // Import Java I/0 classes // the main method public 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, input File, 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 input File.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 C ZOOM + CS 110, Programming Fundamentals I Lab 6: Files and methods Upload to Canvas 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 ReadFileLineByLine.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. 3. 4. . CWU Computer Science . 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.io.*; 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 I/O capabilities. 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? Follow the instructions in the pseudocode in the ReadFileLineByLine.java file: Declare a variable, myFileName, 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); Page 1 of 12 ZOOM + Upload to Canvas 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 ReadFileLineByLine.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. Computer Science 3. 4. 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.io.*; 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 I/O capabilities. 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? Follow the instructions in the pseudocode in the ReadFileLineByLine.java file: . Declare a variable, myFileName, 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, input File, 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 CS110, Tatiana Harrison, CWU, Lab 6: processing Files and Writing MethodsPage 1 of 12 Page 1 of 12 ZOOM + . done before several times, use the following template: Scanner inputFile = new Scanner (file); Increment loop Num by 1 Declare variable fileLine as a String, and assign it the value inputFile.nextLine() 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 input File.close(); 5. Compile and run your program. The output should print to the screen, every 7th ASCII image should be something that you can easily recognize. II. Generating Random Numbers Declare a variable, loop Num, of type int, and assign it the value 0 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 inputFile is not yet pointing to the end of the file. At each iteration of the while loop: 2. a. 3. b. C. 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. I know you are busy, so I will guess your lottery numbers for you! How many numbers should I guess? 3 What is the highest possible lottery number? 98 The first lottery Number is: 63 The next lottery Number is: 82 The last lottery Number is: 79 Good luck! User indicates 3 numbers, no greater than 98 I know you are busy, so I will guess your lottery numbers for you! How many numbers should I guess? 7 What is the highest possible lottery number? 7845 The first lottery Number is: 7175 The next lottery Number is: 2272 The next lottery Number is: 6106 The next lottery Number is: 903 The next lottery Number is: 3291 The next lottery Number is: 328 The last lottery Number is: 182 Good luck! file, and the I know you are busy, so I will guess your lottery numbers for you! How many numbers should I guess? 5 What is the highest possible lottery number? 7634543 User indicates 7 numbers, no greater than 7845 Figure 1: Sample invocations of GenerateSome RandomLotteryNums java The first lottery Number is: 7590308 The next lottery Number is: 4283235 The next lottery Number is: 4609907 The next lottery Number is: 6447816 The last lottery Number is: 560108 Good luck! To complete this programming task: 1. Create new file in jGRASP. Call it GenerateSomeRandomLotteryNums.java, and save it. The program uses the Scanner and Random classes, so you must import them at the top of the file: import java.util.Scanner; import java.util.Random; Write a main method, that prints to the screen the following instructions (use a combination of println User indicates 5 numbers, no greater than 7634543 Page < 2 of 12 ZOOM + 4. 5. 6. 7. 8. 9. 10. 11. and print statements, as necessary): I know you are busy, so I will guess your lottery numbers for you! How many numbers should I guess? Set up a Scanner object; tell it to listen to the keyboard, by writng System. in in the constructor. Declare a variable of type int, and use the nextInt () method of Scanner, to retrieve from the user. and save into the variable, an integer value. Make your program print to the screen, the following message: What is the highest possible lottery number? 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 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 possibleLotteryNum. 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 (); 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; i++) 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 highest PossibleLotteryNum 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. Compile and run your program, and make sure that you get similar output that is shown in Figure 1. CS110, Tatiana Harrison, CWU, Lab 6: processing Files and Writing MethodsPage 3 of 12 Page < 3 of 12 ZOOM + 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 x 3 x 3 x 3 = 81. Two sample runs of the program are shown in Figure 2. To get started, download and save to your computer, the file MyProgram Without Methods.java. Compile and run the program (Also shown in Figure 3). 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 7th power: 78125 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 1 // import statements 2 import java.util.Scanner; 3 4 public class MyProgram Without Methods { 6 7 10 13 14 15 16 17 6227237ERNE 18 10 19 20 21 Figure 2: Two sample runs of the program MyProgramWithoutMethods.java // the main routine public static void main (String[] args) { 27 } 28} // print to the screen, instructions System.out.println("This program calculates the nth power of a base integer input by the user."); System.out.print("Please input your base; an integer less than 10 : "); // receive user's input Scanner keyboard = new Scanner(System.in); int myInteger = keyboard.nextInt(); System.out.print("Please input your exponent; a positive integer less than 10 : "); int myExponent keyboard.nextInt(); int myIntegerPower = myInteger; // perform calculation for (int i = 2; i 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 MyProgramwithoutMethods.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: 1 2. In this step of the lab, you'll write your own displayInstructions method. To do so: Create a new java file. Cut and paste the code from your MyProgram Without Methods.java into the new just-created new java file. 3. 4. // a method that prints instructions public static void display Instructions () { 5. } System.out.println("Hello, this program performs " "a simple calculation"); Change the class name in the new java file to MyProgram WithOne Method, and save the java file as MyProgram WithOneMethod.java 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 returns void, receives zero parameters, and is called print Instructions. The header of the method is the following, which should be written in your java file, above the main method: public static void printInstructions () The body of this new print Instructions method should contain a single println statement: System.out.println("This program calculates the nth power of a base " + "integer input by the user."); Edit the main routine so that instead of: System.out.println ("This program calculates the nth power of a base " + "integer input by the user."); you invoke the print Instructions method: print Instructions (); 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, print Instructions () does not require any input parameters. CS110, Tatiana Harrison, CWU, Lab 6: processing Files and Writing MethodsPage 5 of 12 Page < 5 of 12 ZOOM + 6. 1 // import statements. 2 import java.util.Scanner; 3 4 public class MyProgramWithOneMethod { 5 6 7 8 9 10 11 12 13 14 15 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 WithOneMethod.java file should look similar to Figure 4. 16 17 41 42 43 44} // a method to print instructions public static void print Instructions () { System.out.println("This program calculates the nth power "of a base integer input by the user."); } // a method to read an integer value from the keyboard public static int get IntegerFromKeyboard () { Scanner keyboard = new Scanner (System.in); int keyboardInput = keyboard.nextInt (); return keyboardInput; } // the main routine public static void main (String[] args) { } // print to the screen, instructions print Instructions(); // receive user's input Scanner keyboard = new Scanner(System.in); System.out.print("Please input your base; "an integer less than 10 "); int myInteger = keyboard.nextInt (); System.out.print("Please input your exponent; + "a positive integer less than 10 : "); int myExponent = keyboard.nextInt (); int myIntegerPower = myInteger; // perform calculation for (int i= 2; i IIIb. Adding a getIntegerFromKeyboard() 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: 1. 2. 3. In this step of the lab, you'll add a getInteger 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 exponent integer. The lesson here is that you can reuse a method as many times as needed. To complete this step: 4. 5. // a method that queries a user for a number // and returns the value supplied via the keyboard public static int getUsers Input () { } System.out.println("Please input an integer: "); Scanner keyboard=new Scanner (System.in); int userInput keyboard.nextInt (); System.out.println("You've supplied + userInput); return userInput; Create a new java file and cut and paste the code from your MyProgram WithOneMethod.java into the just-created new java file. } Change the class name in the new java file to MyProgram With TwoMethods, and save the file as MyProgram With TwoMethods.java 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: // a method that instantiates a Scanner class, listens to the keyboard, // retrieves an integer, and returns the value public static int getIntegerFromkeyboard () { Scanner keyboard= new Scanner (System.in); int keyboardInput = keyboard.nextInt (); return keyboardInput; Modify the main method of your program, so that it retrieves the input from the keyboard, using the getIntegerFromKeyboard method: // receive user's input System.out.println("Please input your base; an integer less than 10 : "); int my Integer = getIntegerFromkeyboard (); System.out.println("Please input your exponent; a positive" + "integer less than 10 "); int myExponent = getInteger Fromkeyboard (); int myIntegerPower = myInteger; Be sure to remove the statement Scanner keyboard = new Scanner (System.in); from your main method. Notice how you are using the get Integer FromKeyboard method twice. Compile and debug your program, and make sure that it performs 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 CS110, Tatiana Harrison, CWU, Lab 6: processing Files and Writing MethodsPage 8 of 12 Page < 8 of 12 ZOOM + The following files should be uploaded to Canvas (use the "Add Another File" option to submit multiple files, do not zip): ReadFileLineByLine.java GenerateSomeRandomLotteryNums.java MyProgram WithOneMethod.java MyProgram With TwoMethods.java MyProgram WithThree Methods.java V. Rubric File / task ReadFileLineByLine.java compiles and generates correct ASCII image Generate SomeRandomLotteryNums.java compiles and generates lottery numbers MyProgram WithOneMethod.java compiles and generates correct output MyProgram With Twos Methods.java compiles and generates correct output MyProgram With Three Methods.java compiles and generates correct output All java files are commented, and contain your name and date Variable names are adequate and descriptive in all java files, good code formatting Points 30 30 10 10 10 5 5 Total 100 Page < 12 of 12 ZOOM + import java.util.Scanner; import java.io. *; // Define a new class. public class Read FileLineByLine { } // Import the Scanner class // Import Java I/0 classes // the main method public 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, input File, 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 input File.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 C ZOOM +
Expert Answer:
Answer rating: 100% (QA)
The following is the required source code imports import javautilScanner class public class DecimalMathUsingIntegers main function public static void ... View the full answer
Related Book For
Foundations of Financial Management
ISBN: 978-1259024979
10th Canadian edition
Authors: Stanley Block, Geoffrey Hirt, Bartley Danielsen, Doug Short, Michael Perretta
Posted Date:
Students also viewed these programming questions
-
Design a Java class that represents a cache with a fixed size. It should support operations like add, retrieve, and remove, and it should evict the least recently used item when it reaches capacity.
-
Instructions for the Partnership Exercise: Your assignment is to correct a defective three person partnership agreement. You need to name at least three partners in your partnership agreement. If you...
-
Highland Corporation was organized on January 1, 2017. It is authorized to issue 50,000, $3 noncumulative preferred shares, and an unlimited number of common shares. The following transactions were...
-
Suppose that a life insurance company has guaranteed a payment of $14 million to a pension fund 4.5 years from now. If the life insurance company receives a premium of $10.4 million from the pension...
-
The chemical energy of gasoline is \(46 \mathrm{MJ} / \mathrm{kg}\). If gasoline's mass could be completely converted into energy, what mass of gasoline would be needed to equal the chemical energy...
-
Powell Warehouse distributes hardback books to retail stores and extends credit terms of 2/10, n/30 to all of its customers. During the month of June, the following merchandising transactions...
-
Calculate the decimal equivalents of the following binary numbers: 1. 11011011 2. 01111111 3. 10000000 4. 11000000 5. 11001101
-
Write a program that will ask the user to input the length of one side of the prism and the number of layers of the pryamid. Then, create an equation that calculates the total area of gold foil that...
-
You just purchased a parcel of land for $47,000. To earn a 13% annual rate of return on your investment, how much must you sell the land for in 4 years? Assume annual compounding. (Round to nearest...
-
A company currently pays a dividend of $2.00 per share (i.e., D 0 =$2.0). It is estimated that company's dividend will grow at a rate of 20% per year for the next three years, and the the dividend...
-
Assume the following information You have $420,000 to invest Current spot rate of Sudanese dinar (SDD) = $.00570 90-day forward rate of the dinar = $.00569 90-day interest rate in the U.S. = .04...
-
You just purchased 200 shares of a company stock at $50 per share.The dividend is projected to increase at a constant rate of 4.50% per yr. The required rate of return on the stock is 8.00%. What is...
-
At an exit multiple of 6.5x EBITDA, what would be the total equity value created (i.e., the increase in the equity value the buyer realizes) in this LBO? Format your answer as $1,234.4 as 1234
-
Suppose that y = 2x 5 and y = -3x + 7 are the equations of the tangents to the curves y = f (r) and y = g(x), respectively, at the point where x = 1. Find the slope of the tangent to the curve y =...
-
Differentiate. y = ln(3x + 1) ln(5x + 1)
-
Why are cash flows of more interest than income to the treasury manager?
-
Clyde's Well Servicing has the following financial statements. The balance sheet items, profit margin, and dividend payout have maintained the same relationships the past couple of years; these...
-
The Adams Corporation makes standard-size 2-inch fasteners , which it sells for $155 per thousand. Mr. Adams is the majority owner and manages the inventory and finances of the company. He estimates...
-
Consider the following time series data. a. Construct a time series plot. What type of pattern exists in the data? b. Show the four-quarter and centered moving average values for this time series. c....
-
The following table reports prices and usage quantities for two items in 2009 and 2011. a. Compute price relatives for each item in 2011 using 2009 as the base period. b. Compute an unweighted...
-
Refer to exercise 35. a. Deseasonalize the time series using the adjusted seasonal indexes computed in part (c) of exercise 35. b. Using Minitab or Excel, compute the linear trend regression equation...
Study smarter with the SolutionInn App