Java Chapter 4
This is a special variable that signals when there are no more items from a list of items to be processed. This value cannot be mistaken as an item from the list
sentinel
This is a value that signals when the end of a list of values has been reached
sentinel
prefix
++number or --number Ex: int x=1, y; Y=++x; Increments x to 2 and stores 2 in y and after the code is executed x will also contain 2
example of methods used to read data from a file
// 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();
using a loop to determine if the file has another line to read
// 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.
It is not necessary to initialize accumulator variables T or F
False
One limitation of the for loop is that only one variable may be initialized in the initialization expression T or F
False
The do-while loop is a pretest loop T or F
False
The for loop is a posttest loop T or F
False
To calculate the total number of iterations of a nested loop, add the number of iterations of all the loops T or F
False
To open a file for reading, you use the following classes
File and Scanner
classes used to read data from a file
File and Scanner
Ex of reading data from a file
File myFile=new File ("Customers.txt"); Scanner inputFile=new Scanner(myFile);
2 types of files:
binary and text
continue statement: what is it and should it be used in loops?
causes currently executing iteration to terminate and next iteration begins no
When a program is finished using a file, it should do this.
close the file
what objects throw exceptions and how to we throw them?
PrintWriter and Scanner class public static void main (String[] args) throws IOException
open a file for text output:
PrintWriter outputFile=new PrintWriter("StudentData.txt"); outputFile.println("Chris"); outputFile.close(); If StudentData already exists it will be deleted and replaced
loop
control structure that causes a statement to repeat
loop control variable
controls the number of times the loop iterates
A loop that repeats a specific number of times is known as a(n) ___
counter-controlled loop
counter
counts the number of iterations
for loop
executes as long as the condition exists, performs a known number of iterations
This type of loop is ideal in situations where the exact number of iterations is known
for loop
backslashes and file locations
if a file path contains backslashes you must use 2 of them bc \ is an escape character- this is only if the \ is in a string literal NOT a String object (when the user enters the path)
import statement to use the PrintWriter class
import java.io.*;
import statement for Random class
import java.util.Random; Random randomNumber= new Random();
full random number example
import java.util.Random; Random randomNumber=new Random(); int randNumber=randomNumber.nextInt(1024) +1;
This type of loop has no way of ending and repeats until the program is interrupted.
infinite
If a loop does not contain within itself a way to terminate, it is called a(n) _____
infinite loop
This expression is executed by the for loop only once, regardless of the number of iterations.
initialization expression
nested loops
inner loop executes all of its iterations for each time the other loop executes once
input file vs output file
input is the file that the program reads data from output is the file that a program writes data to
input validation
inspecting data given to a program by the user and determining if it is valid, use the while loop
This type of loop always executes at least once
do-while
How many times will the following do-while loop be executed? int x = 11; do { x += 20; } while (x > 100);
1
What is the output of the following fragment? for (int i = 0; i < 15; i++) { if (i % 4 == 1) System.out.print(i + " "); }
1 5 9 13
Three parts of a loop using the loop control variable
1. Initial/Starting value 2. Increment/Update 3. Check
How many times will the following code print "Welcome to Java"? int count = 0; do { System.out.println("Welcome to Java"); count++; } while (count < 10);
10
How many times will the following code print "Welcome to Java"? int count = 0; while (count < 10) {System.out.println("Welcome to Java"); count++; }
10
nested loop example: How many loop statements execute? for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) loop statements;
100
How many times will the following for loop be executed? for (int count = 10; count <= 21; count++) System.out.println("Java is great!!!");
12
What is the output of the following fragment? int i = 1; int j = 1; while (i < 5) { i++; j = j * 2; } System.out.println(j);
16
How many times are the following loops executed? for (int i = 0; i < 10; i++) for (int j = 0; j < i; j++) System.out.println(i * j)
45
What is the output for y? int y = 0; for (int i = 0; i<10; ++i) { y += i; } System.out.println(y);
45
What will the println statement in the following program segment display? int x = 5; System.out.println(x++);
5
What will the println statement in the following program segment display? int x = 5; System.out.println(++x);
6
Analyze the following code: int x = 1; while (0 < x) && (x < 100) System.out.println(x++); A. The code does not compile because the loop body is not in the braces. B. The code does not compile because (0 < x) && (x < 100) is not enclosed in a pair of parentheses. C. The numbers 1 to 99 are displayed. D. The numbers 2 to 100 are displayed
B. The code does not compile because (0 < x) && (x < 100) is not enclosed in a pair of parentheses
Analyze the following code: (Multiple Answer) public class Test { public static void main (String args[]) { int i = 0; for (i = 0; i < 10; i++); System.out.println(i + 4); } } A. The program has a syntax error because of the semicolon (;) on the for loop line. B. The program compiles despite the semicolon (;) on the for loop line, and displays 4. C. The program compiles despite the semicolon (;) on the for loop line, and displays 14. D. The for loop in this program is same as for (i = 0; i < 10; i++) { }; System.out.println(i + 4);
C. The program compiles despite the semicolon (;) on the for loop line, and displays 14. D. The for loop in this program is same as for (i = 0; i < 10; i++) { }; System.out.println(i + 4);
Analyze the following fragment: double sum = 0; double d = 0; while (d != 10.0) { d += 0.1; sum += sum + d; } A. The program does not compile because sum and d are declared double, but assigned with integer value 0. B. The program never stops because d is always 0.1 inside the loop. C. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers. D. After the loop, sum is 0 + 0.1 + 0.2 + 0.3 + ... + 1.9
C. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers.
Which of the following are pre-test loops? A. while, for, do-while B. while, do-while C. while, for D. for, do-while
C. while, for
A for loop normally performs which of these steps? A. initializes a control variable to a starting value B. test the control variable by comparing it to a maximum/minimum value and terminates when the variable reaches that value C.updates the control variable during each interation D. all of the above
D. all of the above
This type of loop is ideal for situations where you always want the loop to iterate at least once.
do-while loop
How to avoid erasing a file that already exists
First create a FileWriter object: FileWriter fw= new FileWriter ("names.txt", true); Then, create a PrintWriter object: PrintWriter fw=new PrintWriter (fw);
example of random numbers from 1-10
Number=randomNumbers.nextInt(10) +1;
example of random numbers from 0-99
Number=randomNumbers.nextInt(100);
This class allows you to use the print and println methods to write data to a file.
PrintWriter
To open a file for writing, you use the following class
PrintWriter
This class allows you to read a line from a file.
Scanner
What will be the value of x after the following code is executed? int x = 10; do { x *= 20; } while (x > 5);
This is an infinite loop
A variable may be defined in the initialization expression of the for loop T or F
True
In a nested loop, the inner loop goes through all of its iterations for every iteration of the outer loop T or F
True
The while loop is a pretest loop T or F
True
while loop
a Boolean expression that is tested for true or false and a statement that is repeated as long as the expression is true Pretest, runs zero or more times
infinite loop
a loop that does not have a way of stopping
break statement: what is it and should be used in loops?
abnormally terminates a loop no
This is a variable that keeps a running total
accumulator
do-while loop
always performs 1 iteration before testing the Boolean expression Posttest, runs at least once User controlled- user decides the number of iterations
do-while loop general format
do { Statement; Statement; } while (BooleanExpression);
What is each repetition of a loop known as?
iteration
This is a variable that controls the number of iterations performed by a loop
loop control variable
methods of the Random class
nextDouble() returns next random number as a double nextFloat() nextInt() nextInt(int n) returns int between 0 and n
methods used to read data from a file
nextLine nextInt nextDouble
postfix
number++ or number-- ·Ex: int x=1, y; ·Y=x++; Stores 1 in y and after the code is executed then x will contain 2
In the expression number++, the ++ operator is in what mode?
postfix
The do-while loop is this type of loop
posttest
The for loop is this type of loop
pretest
The while loop is this type of loop
pretest
random number between 0 and 1024
randNumber=randomNumber.nextInt(1024) +1;
random numbers method
randomNumbers.nextInt(how many numbers) + starting value
priming read
read operation that takes place just before the loop, provides the first value for the loop to test
buffer
small holding section of memory, when a program writes data to a file it is written to the buffer and when the buffer gets full it writes it to the file- close method causes any unsaved data in the buffer to be written to the file
sentinel values
special value that cannot be mistaken as a member of the list and signals that there are no more values to be entered- loop terminates when the sentinel value is entered
decrement operator
used to decrement the value stored inside the variable it is operating on, --
Increment operator
used to increment the value stored inside the variable it is operating on, ++
accumulator
variable used to accumulate the total of the numbers (running total)
nested loops
when a task performs a repetitive operation and that task itself must be repeated (clock)
exception
when something unexpected happens in a java program an exception is throw
while loop general format
while (BooleanExpression) à aka loop header (1st line in the format) { Statement; Statement; }
input validation- what loop to use and example
while loop ex: if you want a number 1-100 while(number<1 || number>100) { System.out.print("Invalid input. Enter a number in the range of 1 to 100: "); number=keyboard.nextInt(); }
3 loops and difference between them
while, do-while, and for how they control the repetition
appending
writing new data to the end of data that already exists in a file
Do the following two statements in (I) and (II) result in the same value in sum? (I):for (int i = 0; i<10; ++i) { sum += i; } (II):for (int i = 0; i<10; i++) { sum += i; }
yes