Java Ch5 walkthrough

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

59 (5.21) Write code that: opens a file named 'MyName.txt ' and then reads the first line from the file and displays it, then closes the file.

5.21 File file = new File("MyName.txt"); Scanner inputFile = new Scanner(file); if (inputFile.hasNext()) { String str = inputFile.nextLine(); System.out.println(str); } inputFile.close();

25. What will be the value of x after the following statements are executed? int x = 10; for (int y = 5; y < 20; y +=5) x += y; a. 25 b. 30 c. 50 d. 40

d ( 40 )

54 The difference between an input and output file:

Data is read from an input file(The data stored in it serves as input to the program), and data is written to an output file

85. If you attempt to open a file for input in the file does not exist, the program will ...

... throw an exception and halt.

64 initialization expression

...is executed by the for loop only once

78. Throws an 'exception'. What is an exception?

A signal indicating that the program cannot continue until the unexpected event has been dealt with. PrintWriter objects are capable of this. PrintWriter can throw "IOException" types of exceptions. We must either write code that deals with the possible exceptions, or allow our methods to re-throw the exceptions when they occur by writing the "throws IOException" clause in the method header. Additionally, any method that calls a method that uses a PrintWriter object should have a throws IOException clause in it's header.

72. Why do you want to put data in a file?

Because data stored in variables and objects in RAM disappear once the program stops running. The file must be opened... The connection is established between the file and the program. Then the data is written or read. When the program is finished using the file, the file must be closed.

76. Two categories of loops (292)

Conditional( execute as long as the condition exists) and Count controlled(repeats a certain number of times. For example: The loop asks the user for input or when using a 'for' loop which has initialization, test, and update.)

97. Detecting the end of a file

Detecting The End of a File • The Scanner class's hasNext() method will return true if another item can be read from the file. // Open the file. File file = new File(filename); Scanner inputFile = new Scanner(file); // Read until the end of the file. while (inputFile.hasNext()) { String str = inputFile.nextLine(); System.out.println(str); } inputFile.close();// close the file when done.

58 (5.20) What classes do you use to read data from a file?

File and Scanner

73. Put " import java.io.*; ". Near the top of your program

...to work with files in a number of classes in the Java API.

86. How do you determine whether a file exists?

File class's exists method if (!file.exists( ) ) //this is how it looks or <...> if (file.exists( ) ) ............

15. When working with the PrintWriter class, which of the following import statements should you have near the top of your program? a. import javax.swing.*; b. import javac.io.*; c. import java.io.*; d. import java.file.*;

c ( import java.io.*; )

20. Which of the following is the method you can use to determine whether a file exists? a. the File class's canOpen method b. the Scanner class's exists method c. the File class's exists method d. the PrintWriter class's fileExists method

c ( the File class's exists method )

6. A loop that executes as long as a particular condition exists is called a(n) __________ loop. a. infinite b. count-controlled c. conditional d. relational

c (conditional)

12. The __________ loop is ideal in situations where you always want the loop to iterate at least once. a. for b. while c. do-while d. posttest

c (do-while)

92. PrintWriter class

PrintWriter outputFile = new PrintWriter("Names.txt"); //Open the file outputFile.println("Chris"); //writes data to the file outputFile.println("Kathryn"); //writes data to the file outputFile.println("Jean"); //writes data to the file outputFile.close(); //Closes the file

35. In a for loop, the control variable is always incremented.

f

36. The for loop is a posttest loop that has built-in expressions for initializing, testing, and updating.

f

40. The while loop is always the best choice in situations where the exact number of iterations is known.

f (don't forget to write code in the body that modifies the loop control variable. If the loop never becomes false, the loop will repeat indefinitely).

83. Necessary steps when writing a program that reads data from a file

import java.util.Scanner <...>import java.io.*; <...>throws IOException(in method header)<...> Create a File object and pass the name of the file as a string to the constructor<...> create a Scanner object and pass a reference to the File object as an argument to the constructor<...> Use the Scanner class's nextLine method to read a line from a file. (Primitive values are different)<...> call the Scanner class's hasNext method to check for more data to read<...> When finished, use the Scanner class's close method

31. You can use the PrintWriter class to open a file and write data to it.

t

57 Write code that: opens a file named 'MyName.txt' and then writes your first name to the file and then closes the file.

// This is how Kathryn would write the code. PrintWriter outputFile = new PrintWriter("MyName.txt"); outputFile.println("Kathryn"); outputFile.close();

43 What will the following program segments display? x=2; System.out.println(--x);

1

41 What will the following program segments display? x=2; y=x++; System.out.println(y);

2

42 What will the following program segments display? x=2; System.out.println(x++);

2

74. Java has (number) looping control structures

3 (while, do while, and the for)

44 What will the following program segments display? x=8; y=x--; System.out.println(y);

8

49 Accumulator

A variable and pattern designed to keep a running total through multiple iterations

62 postfix operator

An operator placed after a variable. 276

FileWriter fwriter = new FileWriter("MyFriends.txt" , true); PrintWriter outputFile = new PrintWriter ( fwriter ); What does this do? 79.

Appends data to existing file. Create the instance of the file writer class. Pass 2 arguments to the file writer constructor: a string of the name of the file, and (the Boolean) true. Then we create the PrintWriter object so that we can use the print and println methods to write data to the file. Then we pass a reference to the FileWriter object as an argument to the PrintWriter constructor. The FileWriter class also throws and IOException if the file cannot be opened for any reason. (Reference to 60)

82. Use the Scanner class to read input from a file "Customers.txt".

File myFile = new File("Customers.txt); // creates File object instance. File class in Java API Scanner inputFile = new Scanner(myFile); //creates a Scanner object that uses the file //"Customers.txt" as input source

45 Name the three expressions that appear inside the ( ) in the for loop's header?

Initialization, test, and update(use semicolons to separate the initialization, and test expressions in a for loop. Then only the () is after the update. But if you have more than one variable that you are updating testing or initializing, then use commas between each individual segment. And example will follow). (. for ( int x=1, y=6; ... ; x++ , - - y)

46 Write a for loop that displays "I love this" 50 times. The control variable is "count". What are these?: Initialization, test, and update. Write the loop.

Initialization: count = 1 test: count <= 50 update: count++ Write the loop: for (int count = 1; count <= 50; count++) System.out.println("I love this")

70. Tell me about the continue statement in a loop.

It causes the current iteration of a loop to immediately end and it jumps to the next iteration.. In a while loop, this means the program jumps to the Boolean expression at the top of the loop. So, if the expression is still true, the next iteration begins. In a do while loop, the program jumps to the Boolean expression at the bottom of the loop, which determines whether the next iteration will begin. In a for loop, "continue" causes the update expression to be executed, and then the test expression is evaluated. The "continue" statement should also be avoided. It bypasses the loop's logic and makes the code difficult to understand and debug.

75. loop header

It consists of the key word (while/for) followed by an boolean expression enclosed in parenthesis.

80. Specifying a File Location

On a Windows computer, paths contain \ characters. When a single backslash character appears in a string literal, it marks the beginning of an escape sequence like "\n". Two \ \ characters in a string literal represent a single \. So when you provide a path in a string literal and the path contains \ characters, you must use (2) \\ characters in the place of each single \ character. You only use double \ \ if the file path is in a string literal (" "). Java allows you to substitute / for \\ in a windows path(" ").

68a. for loop ( & how many variables can you use in the initialization?)

Pre-test loop. This loop is great for doing a known number of iterations.....count controlled for example. It has built-in expressions for initialization, testing, and updating. That's why it's convenient to use a loop control variable as a counter. Ideal in situations were the exact number of iterations is known. (You can initialize multiple variables power point & p299). Variables declared in this section have scope only for the for loop

56 What class do you use to write data to a file?

PrintWriter

96c. Reading data from a file

Reading Data From a File Once an instance of Scanner is created, data can be read using the same methods that you have used to read keyboard input (nextLine, nextInt, nextDouble, etc). // Open the file. File file = new File("Names.txt"); Scanner inputFile = new Scanner(file); // Read a line from the file. String str = inputFile.nextLine(); // Close the file. inputFile.close();

96b. Reading data from a file

Reading Data From a File Scanner keyboard = new Scanner(System.in); System.out.print("Enter the filename: "); String filename = keyboard.nextLine(); File file = new File(filename); Scanner inputFile = new Scanner(file); • The lines above: - CreatesaninstanceoftheScannerclasstoreadfromthe keyboard - Prompt the user for a filename - Get the filename from the user - Create an instance of the File class to represent the file - CreateaninstanceoftheScannerclassthatreadsfromthefile

52 (5.13) Write a for loop that repeats 7 times, asking the user to enter a number. The loop should also calculate the sum of numbers entered.

Scanner keyboard = new Scanner(System.in); int number = 0, total = 0; for (int i = 1; i <= 7; i++) { System.out.print("Enter a number: "); number = keyboard.nextInt(); total += number; }

71. What do you use to read data from a file and write data to a file?

Some Java API classes. To write data you can use the PrintWriter class and optionally, the FileWriter class. To read data from a file you can use the Scanner class and the File class

77. If you wish to combine multiple Boolean expressions in the test expression, you must use the && or || symbols. T/F

T (300)

93. Exceptions in Java (PowerPoint)

The method that's executing when the exception is thrown must handle the exception or pass it up the line. Handling the exception will be discussed later. To pass it up the line, the method needs a throws clause in the method header

94. Appending Text to a File (PP)

To avoid erasing a file that already exists, create a FileWriter object in this manner: FileWriter fw = new FileWriter("names.txt", true); • Then,createaPrintWriterobjectinthis manner: PrintWriter fw = new PrintWriter(fw);

91. Writing Text to a file(PowerPoint)

To open a file for text output you create an instance of the PrintWriter class. Example: PrintWriter outputFile = new PrintWriter ("StudentData.txt"); /* "StudentData.txt" is the name of the file that you wish to open as an argument to the *PrinterWriter constructor. If the file already exists, it will be erased and replaced with a new *file. */

69. Tell me about the break statement in the loop.

When encountered in a loop, the loop stops, and the program jumps to the statement immediately following the loop. It's common to use a break in a switch statement. It's "taboo" in a loop because it bypasses the normal condition required to terminate the loop and makes code difficult to understand and debug. Avoid using the break statement in a loop when possible.

60 (5.22) You are opening an existing file for output. How do you open the file w/o erasing it, and at the same time, make sure that new data written to the file is appended to the end of the file's existing data?

You create an instance of the FileWriter class to open the file. You pass the name of the file (a string) as the constructor's first argument, and the boolean value true as the second argument. Then, when you create an instance of the PrintWriter class, you pass a reference to the FileWriter object as an argument to the PrintWriter constructor. The file will not be deleted if it already exists and new data will be written to the end of the file

53 Why should you be careful when choosing a sentinel value?

You should be careful to choose a value that cannot be mistaken as a valid input value.

22. What will be the value of x after the following code is executed? int x = 10; while (x < 100) { x += 100; } a. 100 b. 90 c. 110 d. 10

a ( 100 ) (? OK, the teacher said that this was incorrect that the answer should be 110)

26. How many times will the following do-while loop be executed? int x = 11; do { x += 20; } while (x <= 100); a. 5 b. 4 c. 3 d. 1

a ( 5 )

8. The variable used to keep a running total in a loop is called a(n) __________. a. accumulator b. sentinel c. summation d. integer

a (accumulator)

1. A loop that repeats a specific number of times is known as a(n) a. count-controlled b. infinite c. conditional d. pretest

a (count-controlled)

11. The __________ loop is ideal in situations where the exact number of iterations is known. a. for b. while c. do-while d. posttest

a (for)(has a initial value; test; update then no ; but the last parenthesis)

4. Before entering a loop to compute a running total, the program should first a. set the accumulator variable to an initial value, often zero b. set all variables to zero c. read all the values into main memory d. know exactly how many values there are to total

a (set the accumulator variable to an initial value, often zero)

89. Nested loops

a loop inside a loop. The interloop will execute all of it sideration for each time the Outerloop executes wants. This is like the Clock example.

51 sentinel value

a pre-selected value that stops the execution of a program

63 (282) loop control variable

a variable that controls the number of times the loop iterates

50 running total

accumulated sum of numbers from each repetition of loop

30. Select all that apply. Which of the following steps is normally performed by a for loop? a. update the control variable during each iteration b. test the control variable by comparing it to a maximum or minimum value c. terminate when the control variable reaches its maximum or minimum value d. initialize the control variable to a starting value

all ( A, B, C, D )

65 PrintWriter class

allows you to write data to a file using the print and println methods, as you have been using to display data on the screen. If a file that you are opening with the PrintWriter object already exists, it will be erased, then an empty file with the same name will be created.

24. How many times will the following do-while loop be executed? int x = 11; do { x += 20; } while (x > 100); a. 0 b. 1 c. 5 d. 4

b ( 1 )

27. How many times will the following for loop be executed? for (int count = 10; count <= 21; count++) System.out.println("Java is great!"); a. 0 b. 12 c. 10 d. 11

b ( 12 )

29. What will be the value of x after the following code is executed? int x = 10, y = 20; while (y < 100) { x += y; y += 20; } a. 130 b. 210 c. 110 d. 90

b ( 210 )

17. Which of the following statements opens a file named MyFile.txt and allows you to read data from it? a. Scanner inputFile = new Scanner("MyFile.txt"); b. File file = new File("MyFile.txt"); Scanner inputFile = new Scanner(file); c. File Scanner = new File("MyFile.txt"); d. PrintWriter inputFile = new PrintWriter("MyFile.txt");

b ( File file = new File("MyFile.txt"); Scanner inputFile = new Scanner(file); )

18. Which of the following statements opens a file named MyFile.txt and allows you to append data to its existing contents? a. FileWriter fwriter = new FileWriter("MyFile.txt"); PrintWriter outFile = new PrintWriter(fwriter); b. FileWriter fwriter = new FileWriter("MyFile.txt", true); PrintWriter outFile = new PrintWriter(fwriter); c. PrintWriter outfile = new PrintWriter("MyFile.txt", true); d. PrintWriter outfile = new PrintWriter(true, "MyFile.txt");

b ( FileWriter fwriter = new FileWriter("MyFile.txt", true); PrintWriter outFile = new PrintWriter(fwriter); )

21. What does the following code do? Scanner keyboard = new Scanner(System.in); String filename; System.out.print("Enter the filename: "); filename = keyboard.readString(); PrintWriter outFile = new PrintWriter(filename); a. It writes to a file named filename. b. It allows the user to enter the name of the file that data will be written to. c. It establishes a connection with a file named filename. d. Nothing; the code contains a syntax error.

b ( It allows the user to enter the name of the file that data will be written to. )

5. An item that separates other items is known as a a. partition b. delimiter c. sentinel d. terminator

b ( delimiter )

3. A __________ is a value that signals when the end of a list of values has been reached. a. terminal b. sentinel c. token d. delimiter

b ( sentinel )

10. In all but very rare cases, loops must contain, within themselves a. nested loops b. a way to terminate c. arithmetic operators d. nested decision strucures

b (a way to terminate)

2. A __________ loop will always be executed at least once. a. pretest b. posttest c. conditional d. user-controlled

b (posttest )

7. A(n) __________ is a special value that cannot be mistaken as a member of a list of data items and signals that there are no more data items to be processed. a. accumulator b. sentinel c. delimiter d. terminator

b (sentinel)

9. In general, there are two types of files which are... a. encrypted and unencrypted b. delimited and unlimited c. text and binary d. static and dynamic

c (text (plain text and opened in a text editor like Notepad)and binary)

81. Reading data: Scanner keyboard = new Scanner(System.in);

creates a Scanner object for keyboard input. "System.in" represents the keyboard. Passing "System.in" as an argument to the scanner constructor specifies that the keyboard is the scanner object's source of input.

28. What will be the value of x after the following code is executed? int x, y = 15; x = y--; a. 14 b. 16 c. 0 d. 15

d ( 15 )

19. Given the following statement, which statement will write the string "Calvin" to the file DiskFile.txt? PrintWriter diskOut = new PrintWriter("DiskFile.txt"); a. System.out.println(diskOut, "Calvin"); b. PrintWriter.println("Calvin"); c. DiskFile.println("Calvin"); d. diskOut.println("Calvin");

d ( diskOut.println("Calvin"); )

16. Assuming that inputFile references a Scanner object that was used to open a file, which of the following statements will read an int from the file? a. int number = inputFile.next(); b. int number = inputFile.integer(); c. int number = inputFile.readInt(); d. int number = inputFile.nextInt();

d ( int number = inputFile.nextInt(); )

14. Assume that inputFile references a Scanner object that was used to open a file. Which of the following while loops is the correct way to read data from the file until the end of the file is reached? a. while (inputFile.nextLine == " ") b. while (inputFile != null) c. while (!inputFile.EOF) d. while (inputFile.hasNext())

d ( while (inputFile.hasNext()) )

23. What will be the values of x and y as a result of the following code? int x = 25, y = 8; x += y++; a. x = 34, y = 9 b. x = 25, y = 8 c. x = 33, y = 8 d. x = 33, y = 9

d ( x = 33, y = 9 )

13. If a loop does not contain, within itself, a valid way to terminate, it is called a(n) __________ loop a. for b. while c. do-while d. infinite

d (infinite)

32. When the break statement is encountered in a loop, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration.

f

47 Write a for loop that displays your name 10 times

for (int i = 1; i <= 10; i++) System.out.println("Chloe Ashlyn");

48 Write a for loop that displays odd numbers from 1-49 inclusive.

for (int i = 1; i <= 49; i += 2) System.out.println(i);

68c. Multiple initializations and updates example

for(int i=5, int j=0; i<10 || j<20 ; i++, j+=2) { statement(s) ; }. //The semicolons are mandatory... for( ; ; ) // if left out, the test section defaults to true. (PowerPoint)

55 What import statement will you need in a program that performs file operations?

import java.io.*;

88. postfix notation in an expression (x++, x- -) that is incremented or decremented

indicates that the variable will be incremented or decremented after the rest of the equation has been evaluated

87. prefix notation in an expression(++x, —x) thats incremented or decremented

indicates that the variable will be incremented or decremented prior to the rest of the equation being evaluated

67 do-while loop

post-test loop, ideal in situations where you always want the loop to iterate at least once. Don't forget to put a semicolon at the end of the do while loop

66 while loop

pre-test loop. Ideal in situations where you do not want the loop to iterate if the condition is false from the beginning. It is also ideal if you want to use a sentinel value to terminate the loop.

33. When the continue statement is encountered in a loop, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration.

t

34. A file must always be opened before using it and closed when the program is finished using it.

t

38. When you pass the name of a file to the PrintWriter constructor and the file already exists, it will be erased and a new empty file with the same name will be created.

t

39. When you open a file with the PrintWriter class, the class can potentially throw an IOException.

t

84. When you use a PrintWriter object to open a file, the file will be deleted if it already exists. T / F

t

37. The do-while loop is ideal in situations where you always want the loop to iterate at least once.

t (don't forget to write code in the body that modifies the loop control variable. If a boolean expression never becomes false, the loop will repeat indefinitely. )

68b. update expression in a for loop

this expression executes last in the loop; a statement that increments the loop's control variable(counter) that is declared in the initialization section of the for loop. The update section may update multiple variables. Each variable updated is executed as if it were on a line by its self. Avoid updating the control variable of a for loop within the body of the loop. You should use the update section. Updating in the body leads to hard to maintain code and difficult debugging. (PowerPoint)

61 (5.23) What clause must you write in the header of a method that performs a file operation?

throws IOException

90. When and where should you use the three types of loops?

while: pretest; use it where you do not want the statements to execute if the condition is false in the beginning do-while: post test loop; use it if you want the statements to execute at least once for: pretest loop; use it where there is some type of counting variable that can be evaluated.

95. Specifying a File Location (PP)

• On a Windows computer, paths contain backslash (\) characters. • Remember, if the backslash is used in a string literal, it is the escape character so you must use two of them: PrintWriter outFile = new PrintWriter("A:\\PriceList.txt"); This is only necessary if the backslash is in a string literal. • If the backslash is in a String object then it will be handled properly. • Fortunately, Java allows Unix style filenames using the forward slash (/) to separate directories: PrintWriter outFile = new PrintWriter("/home/rharrison/names.txt");

96a. Reading data from a file(PP)

• You use the File class and the Scanner class to read data from a file: Pass the name of the file as an argument to the File class constructor. File myFile = new File("Customers.txt"); Scanner inputFile = new Scanner(myFile); Pass the File object as an argument to the Scanner class constructor.


Kaugnay na mga set ng pag-aaral

Chapter 50: Behavior, Cognition, Development, or Mental Health/Cognitive or Mental Health Disorder

View Set

Chemistry Unit 4: Chemistry of Climate Change: Part 2 Lesson 1

View Set

AMSCO CHAPTER 10, PAPUSH: The Age of Jackson

View Set