Chapter 4 Java Loops and Files

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

for (int value = -5; value < 5; value++) System.out.println(value);

-5 -4 -3 -2 -1 0 1 2 3 4

d) x = 8; y = x--; System.out.println(y);

8

What update expression will you use?

c) count++

This type of loop always executes at least once.

do-while

True or False: It is not necessary to initialize accumulator variables.

false

True or False: The for loop is a posttest loop.

false

How many times will "Hello World" be printed in the following program segment? int count = 10; while (count < 1) { System.out.println("Hello World"); count++; }

0 times

int x; for (x = 5; x <= 14; x += 3) System.out.println(x); System.out.println(x);

5 8 11 14 17

How does a file buffer increase a program's performance?

A buffer is a small "holding section" of memory. When a program writes data to a file, that data is first written to the buffer. When the buffer is filled, all the information stored there is written to the file. This technique increases the system's performance because writing data to memory is faster than writing it to a disk. The close method writes any unsaved data remaining in the file buffer.

Describe the difference between pretest loops and posttest loops.

A pretest loop tests its test expression before each iteration. A posttest loop tests its test expression after each iteration.

When writing data to a file, what is the difference between the print and the println methods?

After the println method writes its data, it writes a newline character. The print method does not write the newline character.

Why is it critical that accumulator variables are properly initialized?

An accumulator is used to keep a running total of numbers. In a loop, a value is usually added to the current value of the accumulator. If it is not properly initialized, it will not contain the correct total.

How many times will "I love Java programming!" be printed in the following program segment? int count = 0; while (count < 10) System.out.println("I love Java programming!);

This must be a trick question. The statement that prints "I love Java programming!" is not in the body of the loop. The only statement that is in the body of the loop is the one that prints "Hello World". Because there is no code in the loop to change the contents of the count variable, the loop will execute infinitely, printing "Hello World". So, "I love Java programming!" is never printed.

To open a file for writing, you user the following class.

printWriter

What will the following program segments display? a) for (int count = 0; count < 6; count++) System.out.println(count + count);

0 2 4 6 8 1

c) x = 2; System.out.println(--x);

1

What will the println statement in the following program segment display? int x = 5; System.out.println(++x);

6

Write a for loop that displays your name 10 times.

// This is how Chloe Ashlyn would write the loop. for (int i = 1; i <= 10; i++) System.out.println("Chloe Ashlyn");

Write code that does the following: opens a file named MyName.txt, 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();

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

2

b) x = 2; System.out.println(x++);

2

What will the println statement in the following program segment display? int x = 5; System.out.println(x++);

5

Why are the statements in the body of a loop called conditionally executed statements?

Because they are only executed when a condition is true

Why should you indent the statements in the body of a loop?

By indenting the statements, you make them stand out from the surrounding code. This helps you to identify at a glance the statements that are conditionally executed by a loop.

Why should a program close a file when it's finished using it?

Closing a file writes any unsaved data remaining in the file buffer.

What is the difference between an input file and an output file?

Data is read from an input file, and data is written to an output file.

Briefly describe the difference between the prefix and postfix modes used by the increment and decrement operators.

In postfix mode the operator is placed AFTER the operand. In prefix mode the operator is placed BEFORE the variable operand. Postfix mode causes the increment or decrement operation to happen AFTER the value of the variable is used in the expression. Prefix mode causes the increment or decrement to happen BEFORE.

Name the three expressions that appear inside the parentheses in the for loop's header.

Initialization, test, and update.

This class allows you to read a line from a file.

Scanner

What is a potential error that can occur when a file is opened for reading?

The file does not exist.

Why must the value chosen for use as a sentinel be carefully selected?

The value chosen for a sentinel must be carefully selected because you want it to be unique enough that it will not be mistaken for a regular value in a list you are working with.

Describe the difference between the while loop and the do-while loop.

The while loop is a pretest loop and the do - while loop is a posttest loop.

How do you open a file so that new data will be written 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 erased if it already exists and new data will be written to the end of the file.

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.

You want to write a for loop that displays "I love to program" 50 times. Assume that you will use a control variable named count. a) What initialization expression will you use?

a) count = 1

This is a variable that keeps a running total.

accumulator

What test expression will you use?

b) count <= 50

What does it mean to let the user control a loop?

controls the number of times the iterations performed by a loop.

Write the loop.

d) for (int count = 1; count <= 50; count++) System.out.println("I love to program");

True or False: One limitation of the for loop is that only one variable may be initialized in the initialization expression.

false

True or False: The do-while loop is a pretest loop.

false

True or False: To calculate the total number of iterations of a nested loop, add the number of iterations of all the loops.

false

What does the Scanner class's hasNext method return when the end of the file has been reached?

false

To open a file for reading, you use the following classes.

file and scanner

Write a for loop that displays every fifth number, zero through 100.

for (int i = 0; i <= 100; i += 5) System.out.println(i);

Write a for loop that displays all of the odd numbers, 1 through 49.

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

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

import java.io.*;

This type of loop has no way of ending and repeats until the program is interrupted.

infinite

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

What is a file's read position? Where is the read position when a file is first opened for reading?

marks the location of the next item that will be read from the file. When a file is opened, its read position is set to the first item in the file. When the item is read, the read position is advanced to the next item in the file. As subsequent items are read, the internal read position advances through the file.

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

This class allows you to use the print and println methods to write data to a file.

printWriter

This is a special value 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

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

throws IOException

True or False: A variable may be defined in the initialization expression of the for loop.

true

True or False: In a nested loop, the inner loop goes through all of its iterations for every iteration of the outer loop

true

What does it mean to append data to a file?

writing new data to the end of the data that already exists in the file.

What is an infinite loop? Write the code for an infinite loop.

An infinite loop is a loop that has no way of stopping, it occurs when a programmer forgets to write code inside the loop that makes the test condition false. There are several possibilities to do an endless loop, here are a few I would choose: for(;;) {} while(1) {} / while(true) {} do {} while(1) / do {} while(true)

What classes do you use to read data from a file?

File and Scanner

Write code that does the following: opens a file named MyName.txt, reads the first line from the file and displays it, and then closes the file.

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

Assume x is an int variable, and rand references a Random object. What does the following statement do? x = rand.nextInt(100);

It assigns the variable x a random integer in the range 0 through 99.

Assume x is an int variable, and rand references a Random object. What does the following statement do? x = rand.nextInt(9) + 1;

It assigns the variable x a random integer in the range 1 through 9.

Assume x is an int variable, and rand references a Random object. What does the following statement do? x = rand.nextInt();

It assigns the variable x a random integer in the range −2,147,483,648 to +2,147,483,647.

Assume x is a double variable, and rand references a Random object. What does the following statement do? x = rand.nextDouble();

It assigns the variable x a random number in the range 0.0 to 1.0.

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

PrintWriter

Write an input validation loop that asks the user to enter a number in the range of 10 through 24.

Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number in the range of 10 - 24: "); number = keyboard.nextInt(); while (number < 10 || number > 24) { System.out.println("That number is not in the range."); System.out.print("Enter a number in the range of 10 - 24: "); number = keyboard.nextInt(); }

Write a for loop that repeats seven times, asking the user to enter a number. The loop should also calculate the sum of the 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;

What is the advantage of using a sentinel?

Sometimes the user has a list of input values that is very long, and doesn't know the number of items there are. When the sentinel value is entered, it signals the end of the list, and the user doesn't have to count the number of items in the list.

Write an input validation loop that asks the user to enter 'Y', 'y', 'N', or 'n'.

String input; Scanner keyboard = new Scanner(System.in); System.out.print("Enter Y, y, N, or n: "); input = keyboard.nextLine(); ch = input.charAt(0); while (ch != 'Y' && ch != 'y' && ch != 'N' && ch != 'n') { System.out.println("Try again."); System.out.print("Enter Y, y, N, or n: "); input = keyboard.nextLine(); ch = input.charAt(0); }

Write an input validation loop that asks the user to enter "Yes" or "No".

String str; Scanner keyboard = new Scanner(System.in); System.out.print("Enter Yes or No: "); str = keyboard.nextLine(); while ((!str.equals("Yes")) && (!str.equals("No"))) { System.out.print("Please enter Yes or No: "); str = keyboard.nextLine(); }

Which loop should you use in situations where you want the loop to repeat until the boolean expression is false, but the loop should execute at least once?

The do - while loop.

Which loop should you use when you know the number of required iterations?

The for loop.

In the following program segment, which variable is the loop control variable (also known as the counter variable) and which is the accumulator? int a, x = 0, y = 0; while (x < 10) { a = x * 2; y += a; x++; } System.out.println("The sum is " + y)

The variable x is the loop control variable and y is the accumulator.

Which loop should you use in situations where you want the loop to repeat until the boolean expression is false, and the loop should not execute if the test expression is false to begin with?

The while loop.

Describe a programming problem that would require the use of an accumulator.

There are many possible examples. A program that asks the user to enter a business's daily sales for a number of days, and then displays the total sales is one example

Describe a programming problem requiring the use of nested loops.

There are many possible examples. One example is a program that asks for the average temperature for each month, for a period of five years. The outer loop would iterate once for each year and the inner loop would iterate once for each month.

You are opening an existing file for output. How do you open the file without erasing it, and at the same time make sure that new data that is 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 erased if it already exists and new data will be written to the end of the file.

When a program is finished using a file, it should do this.

close the file

This expression is executed by the for loop only once, regardless of the number of iterations.

initialization expression

True or False: The while loop is a pretest loop.

true


Set pelajaran terkait

Section 4—3: Avoiding Dangers to the Baby

View Set

Chapter 46- Nursing Care of the Child With an Alteration in Cellular Regulation / Hematologic or Neoplastic Disorder

View Set

Political Statement: from the Universal Declaration of Human Rights; practice & quiz

View Set

Pharmacology practice exam 1 - Hesi

View Set

Unit 1 MCQ Review - AP Classroom

View Set

Chapter 3: Cellular Form and Function

View Set