Introduction to Programming - TXC1
Review 1.01: Explain the difference between using a computer program and programming a computer.
A well-designed computer program is easy to use without any special knowledge. For example, most people can learn to navigate webpages with only a few minutes of practice. On the other hand, programming a computer requires special knowledge about what the computer can fundamentally do and how you would communicate with it through a programming language.
It is easy to confuse the = and == operators. Write a test program containing the statement if (floor = 13) What error message do you get? Write another test program containing the statement count == 0; What does your compiler do when you compile the program?
In the first case when comparing if (floor = 13) you should get the error "Type mismatch: cannot convert from int to boolean". In the statement count == 0; you should get the error "Syntax error on token "==", invalid assignment operator".
Write a program that prints the sum of the first ten positive integers, 1 + 2 + ... + 10.
public class PrintSum { public static void main(String[] args) { System.out.println(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10); } }
Write a method public static int countWords(String str) that returns a count of all words in the string str. Words are separated by spaces. For example, countWords("Mary had a little lamb") should return 5.
/** Count the number of words in a given string. Assume the string is well formed and doesn't have leading or trailing spaces, or multiple spaces in a row. @param str string to count words in @return number of words in str */ public static int countWords(String str) { int count = 1; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == ' ') { count++; } } return count; }
Write a recursive method public static String reverse(String str) that computes the reverse of a string. For example, reverse("flow") should return "wolf". Hint: Reverse the substring starting at the second character, then add the first character at the end. For example, to reverse "flow", first reverse "low" to "wol", then add the "f" at the end.
/** Reverses a string. @param str input string @return reverse of str */ public static String reverse(String str) { if (str.length() > 1) { return reverse(str.substring(1)) + str.charAt(0); } return str; }
Find at least five compile-time errors in the following program. public class HasErrors { public static void main(); { System.out.print(Please enter two numbers:) x = in.readDouble; y = in.readDouble; System.out.printline("The sum is " + x + y); } }
1) There is an extraneous semicolon after main(). 2) The message in the first print statement is not surrounded by quotation marks like a string should be. 3) The variables x and y are not declared. 4) The variable in is not declared. 5) The method readDouble doesn't exist (nextDouble does). 6) If readDouble were a method, it should be followed by (). 7) In the last line the method println is incorrectly spelled printline.
Why is a CD player less flexible than a computer?
A CD player can do one thing—play music CDs. It cannot execute programs.
Define "computer program" and programming
Computers execute very basic instructions in rapid succession. A computer program is a sequence of instructions and decisions. Programming is the act of designing and implementing computer programs.
Describe the process of translating high-level languages to machine code.
Java was originally designed for programming consumer devices, but it was first successfully used to write Internet applets. Java was designed to be safe and portable, benefiting both Internet users and students. Java programs are distributed as instructions for a virtual machine, making them platform-independent. Java has a very large library. Focus on learning those parts of the library that you need for your programming projects.
What is the value of mystery after this sequence of statements? int mystery = 1; mystery = 1 - 2 * mystery; mystery = mystery + 1;
The value of mystery is equal to 0 after the statements are executed. In the first statement (line 1), mystery is initialized to a value of 1. In the assignment statement on line 2, mystery is set to -1. Finally, mystery is set to 0 in line 3.
In which sequence are the lines of the Cubes.java program in Section 5.2 executed, starting with the first line of main?
This is the order in which the lines of code are executed: 8 21 22 9 21 22 10 11
Write a while loop that prints. a. All squares less than n. For example, if n is 100, print 0 1 4 9 16 25 36 49 64 81. b. All positive numbers that are divisible by 10 and less than n. For example, if n is 100, print 10 20 30 40 50 60 70 80 90 c. All powers of two less than n. For example, if n is 100, print 1 2 4 8 16 32 64.
a) int i = 0; while (i * i < n) { System.out.println(i * i); i++; } b) int i = 10; while (i < n) { System.out.println(i); i = i + 10; } c) int i = 1; while (i < n) { System.out.println(i); i = i * 2; }
What is the value of each variable after the if statement? a) int n = 1; int k = 2; int r = n; if (k < n) { r = k; } b) int n = 1; int k = 2; int r; if (n < k) { r = k; } else { r = k + n; } c) int n = 1; int k = 2; int r = k; if (r < k) { n = r; } else { k = n; } d) int n = 1; int k = 2; int r = 3; if (r < n + k) { r = 2 * n; } else { k = 2 * r; }
a) n = 1, k = 2, r = 1 b) n = 1, k = 2, r = 2 c) n = 1, k = 1, r = 2 d) n = 1, k = 6, r = 3
Complete the program in How To 4.1. Your program should read twelve temperature values and print the month with the highest temperature.
import java.util.Scanner; public class HottestMonth { public static void main(String[] args) { Scanner in = new Scanner(System.in); double highestValue; highestValue = in.nextDouble(); int highestMonth = 1; for (int currentMonth = 2; currentMonth<= 12; currentMonth++) { double nextValue = in.nextDouble(); if (nextValue > highestValue) { highestValue = nextValue; highestMonth = currentMonth; } } System.out.println(highestMonth); } }
Write a program that reads in two floating-point numbers and tests whether they are the same up to two decimal places. Here are two sample runs.
import java.util.Scanner; public class SameToTwoDecimalPlaces { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter two floating point numbers: "); double x = in.nextDouble(); double y = in.nextDouble(); if (Math.abs(x - y) < 0.01) { System.out.println("They are the same up to two decimal places."); } else { System.out.println("They are different."); } } }
Number Types
int - The integer type, with range −2,147,483,648 (Integer.MIN_VALUE) ... 2,147,483,647 (Integer.MAX_VALUE, about 2.14 billion) 4 bytes byte - The type describing a single byte consisting of 8 bits, with range −128 ... 127 - 1 byte short - The short integer type, with range −32,768 ... 32,767 2 bytes long - The long integer type, with about 19 decimal digits 8 bytes double - The double-precision floating-point type, with about 15 decimal digits and a range of about ±10308 8 bytes float - The single-precision floating-point type, with about 7 decimal digits and a range of about ±1038 - 4 bytes char - The character type, representing code units in the Unicode encoding scheme (see Random Fact 2.2) - 2 bytes
Write a program that prints the balance of an account after the first, second, and third year. The account has an initial balance of $1,000 and earns 5 percent interest per year.
public class AccountBalance{ public static void main(String[] args) { System.out.println(1000 * 1.05); System.out.println(1000 * 1.05 * 1.05); System.out.println(1000 * 1.05 * 1.05 * 1.05); } }
How do you test whether exactly one of them is zero?
(x = = 0 && y != 0) || (y = = 0 && x != 0)
What is the value of !!frozen?
(x = = 0 && y != 0) || (y = = 0 && x != 0)
What do the following nested loops display? for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { System.out.print(i + j); } System.out.println(); }
0123 1234 2345
How many numbers does this loop print? for (int n = 10; n >= 0; n--) { System.out.println(n); }
11 numbers: 10 9 8 7 6 5 4 3 2 1 0
Consider this method: public static int mystery(int x, int y) { double result = (x + y) / (y - x); return result; } What is the result of the call mystery(2, 3)?
2 + 3) / (3 − 2) = 5
What does the following loop print? int n = 1; while (n < 100) { n = 2 * n; System.out.print(n + " "); }
2 4 8 16 32 64 128 Note that the value 128 is printed even though it is larger than 100.
The Math.ceil method in the Java standard library is described as follows: The method receives a single argument of type double and returns the smallest double value ≥ that is an integer. What is the return value of Math.ceil(2.3)?
3.0
If you make the change in Self Check 38, how many values are displayed?
60: The outer loop is executed 10 times, and the inner loop 6 times.
Suppose we want to have the earthquake program check whether the user entered a negative number. What branch would you add to the if statement, and where?
Add a branch before the final else: else if (richter < 0) { System.out.println("Error: Negative input"); }
How do you modify the program so that it shows the average, not the total, of the inputs?
Add a variable count that is incremented whenever a number is read. In the end, print the average, not the total, as out.printf("Average: %8.2f\n", total / count); Because the string "Average" is three characters longer than "Total", change the other output to out.printf("%18.2f\n", value).
How can you modify the Total program so that it writes the values in two columns, like this: 32.00 54.00 67.50 29.00 35.00 80.00 115.00 44.50 100.00 65.00 Total: 622.00
Add a variable count that is incremented whenever a number is read. Only write a new line when it is even. count++; out.printf("%8.2f", value); if (count % 2 = = 0) { out.println(); } At the end of the loop, write a new line if count is odd, then write the total: if (count % 2 = = 1) { out.println(); } out.printf("Total: %10.2f\n", total);
Consider the following method that computes compound interest for an account with an initial balance of $10,000 and an interest rate of 5 percent: public static double balance(int years) { return 10000 * Math.pow(1.05, years); } How can you make this method more reusable?
Add parameter variables so you can pass the initial balance and interest rate to the method: public static double balance( double initialBalance, double rate, int years) { return initialBalance * pow( 1 + rate / 100, years); }
lexicographic ordering in Java
All uppercase letters come before the lowercase letters. For example, "Z" comes before "a". • The space character comes before all printable characters. • Numbers come before letters. • For the ordering of punctuation marks, see Appendix A. When comparing two strings, you compare the first letters of each word, then the second letters, and so on, until one of the strings ends or you find the first letter pair that doesn't match. If one of the strings ends, the longer string is considered the "larger" one. For example, compare "car" with "cart". The first three letters match, and we reach the end of the first string. Therefore "car" comes before "cart" in lexicographic ordering. When you reach a mismatch, the string containing the "larger" character is considered "larger". For example, let's compare "cat" with "cart". The first two letters match. Because t comes after r, the string "cat" comes after "cart" in the lexicographic ordering.
Why is there a statement System.out.println(); in the outer loop but not in the inner loop?
All values in the inner loop should be displayed on the same line.
Describe a way in which a String object might store its characters.
As an ArrayList<Character>. As a char array.
Using Dialog Boxes for Input and Output
Call the static showInputDialog method of the JOptionPane class, and supply the string that prompts the input from the user. For example, String input = JOptionPane.showInputDialog("Enter price:"); That method returns a String object. Of course, often you need the input as a number. Use the Integer.parseInt and Double.parseDouble methods to convert the string to a number: double price = Double.parseDouble(input); You can also display output in a dialog box: JOptionPane.showMessageDialog(null, "Price: " + price);
How would you change the program to display all powers from to ?
Change lines 13, 18, and 30 to for (int n = 0; n <= NMAX; n++). Change NMAX to 5.
Strings and Characters import java.util.Scanner; /** This program prints a pair of initials. */ public class Initials { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Get the names of the couple System.out.print("Enter your first name: "); String first = in.next(); System.out.print("Enter your significant other's first name: "); String second = in.next(); // Compute and display the inscription String initials = first.substring(0, 1) + "&" + second.substring(0, 1); System.out.println(initials); } } Program Run : Enter your first name: Rodolfo Enter your significant other's first name: Sally R&S
Character literals are delimited by single quotes, and you should not confuse them with strings. • 'H' is a character, a value of type char. • "H" is a string containing a single character, a value of type String. The charAt method returns a char value from a string. The first string position is labeled 0, the second one 1, and so on. H A R R Y 0 1 2 3 4 The position number of the last character (4 for the string "Harry") is always one less than the length of the string. For example, the statement String name = "Harry"; char start = name.charAt(0); char last = name.charAt(4); sets start to the value 'H' and last to the value 'y'.
How do you simulate a coin toss with the Math.random() method?
Compute (int) (Math.random() * 2), and use 0 for heads, 1 for tails, or the other way around.
How do you simulate the picking of a random playing card?
Compute (int) (Math.random() * 4) and associate the numbers 0 ... 3 with the four suits. Then compute (int) (Math.random() * 13) and associate the numbers 0 ... 12 with Jack, Ace, 2 ... 10, Queen, and King.
Finding the First Match (Loop)
Here is a loop that finds the first space in a string. Because we do not visit all elements in the string, a while loop is a better choice than a for loop: boolean found = false; char ch = '?'; int position = 0; while (!found && position < str.length()) { ch = str.charAt(position); if (ch = = ' ') { found = true; } else { position++; } } If a match was found, then found is true, ch is the first matching character, and position is the index of the first match. If the loop did not find a match, then found remains false after the end of the loop. Note that the variable ch is declared outside the while loop because you may want to use the input after the loop has finished. If it had been declared inside the loop body, you would not be able to use it outside the loop.
Consider the algorithm to find the largest element in an array. Why don't we initialize largest and i with zero, like this? double largest = 0; for (int i = 0; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }
If all elements of values are negative, then the result is incorrectly computed as 0.
What is wrong with these statements for printing an array with separators? System.out.print(values[0]); for (int i = 1; i < values.length; i++) { System.out.print(", " + values[i]); }
If the array has no elements, then the program terminates with an exception.
What is wrong with the following loop for reading a sequence of values? System.out.print("Enter values, Q to quit: "); do { double value = in.nextDouble(); sum = sum + value; count++; } while (in.hasNextDouble());
If the user doesn't provide any numeric input, the first call to in.nextDouble() will fail.
When finding the position of a match, we used a while loop, not a for loop. What is wrong with using this loop instead? for (pos = 0; pos < values.length && !found; pos++) { if (values[pos] > 100) { found = true; } }
If there is a match, then pos is incremented before the loop exits.
Prompting Until a Match is Found (Loop)
In the preceding example, we searched a string for a character that matches a condition. You can apply the same process to user input. Suppose you are asking a user to enter a positive value . Keep asking until the user provides a correct input: boolean valid = false; double input = 0; while (!valid) { System.out.print("Please enter a positive value < 100: "); input = in.nextDouble(); if (0 < input && input < 100) { valid = true; } else { System.out.println("Invalid input."); } } Note that the variable input is declared outside the while loop because you will want to use the input after the loop has finished.
How do you generate a random floating-point number and ?
Math.random() * 100.0
What does the SentinelDemo.java program print when the user immediately types when prompted for a value?
No data
Suppose the user enters −1 into the earthquake program. What is printed?
No destruction of buildings.
Suppose the providers of your Java compiler decide to change the way that a String object stores its characters, and they update the String method implementations accordingly. Which parts of your code do you need to change when you get the new compiler?
None. The methods will have the same effect, and your code could not have manipulated String objects in any other way.
Is the method call "Hello, World".println() legal? Why or why not?
No—the object "Hello, World" belongs to the String class, and the String class has no println method.
How do you find the position of the last space in a string?
Start the loop at the end of string: boolean found = false; int i = str.length() - 1; while (!found && i >= 0) { char ch = str.charAt(i); if (ch = = ' ') { found = true; } else { i--; } }
Declare an array called words that can hold ten elements of type String.
String[] words = new String[10];
Declare an array containing two strings, "Yes", and "No".
String[] words = { "Yes", "No" };
Consider the method call Math.pow(3, 2). What are the arguments and return values?
The arguments are 3 and 2. The return value is 9.
What is wrong with the following statement? System.out.print(boxString("Hello"));
The boxString method does not return a value. Therefore, you cannot use it in a call to the print method.
In many games, you throw a pair of dice to get a value between 2 and 12. What is wrong with this simulated throw of a pair of dice? int sum = (int) (Math.random() * 11) + 2;
The call will produce a value between 2 and 12, but all values have the same proba-bility. When throwing a pair of dice, the number 7 is six times as likely as the num-ber 2. The correct formula is int sum = (int) (Math.random() * 6) + (int) (Math.random() * 6) + 2;
Why does the SentinelDemo.java program have two checks of the form salary != -1
The first check ends the loop after the sentinel has been read. The second check ensures that the sentinel is not processed as an input value.
Beginners sometimes write statements such as the following: if (price > 100) { discountedPrice = price - 20; } else if (price <= 100) { discountedPrice = price - 10; } Explain how this code can be improved.
The if (price <= 100) can be omitted (leaving just else), making it clear that the else branch is the sole alternative.
What is the return value of the method call Math.pow(Math.pow(2, 2), 2)?
The inner call to Math.pow returns . Therefore, the outer call returns
What is wrong with the following loop for finding the position of the first space in a string? boolean found = false; for (int position = 0; !found && position < str.length(); position++) { char ch = str.charAt(position); if (ch = = ' ') { found = true; } }
The loop will stop when a match is found, but you cannot access the match because neither position nor ch are defined outside the loop.
In the last example of this section, we prompt the user "Enter values, Q to quit." What happens when the user enters a different letter?
The nextDouble method also returns false. A more accurate prompt would have been: "Enter values, a key other than a digit to quit." But that might be more con-fusing to the program user who would need now ponder which key to choose.
What happens when you supply the name of a nonexistent input file to the Total program? Try it out if you are not sure.
The program throws a FileNotFoundException and terminates.
What is the advantage of using the type boolean rather than strings "false"/"true" or integers 0/1?
The same as the value of frozen.
switch statement
The switch statement can be applied only in narrow circumstances. The values in the case clauses must be constants. They can be integers or characters. As of Java 7, strings are permitted as well. You cannot use a switch statement to branch on floating-point values. Every branch of the switch should be terminated by a break instruction. If the break is missing, execution falls through to the next branch, and so on, until a break or the end of the switch is reached. In practice, this fall-through behavior is rarely useful, but it is a common cause of errors. If you accidentally forget a break statement, your program compiles but executes unwanted code. Many programmers consider the switch statement somewhat dangerous and prefer the if statement. We leave it to you to use the switch statement for your own code or not. At any rate, you need to have a reading knowledge of switch in case you find it in other programmers' code.
What would happen if the declaration of the salary variable in SentinelDemo.java was changed to double salary = -1;
The while loop would never be entered. The user would never be prompted for input. Because count stays 0, the program would then print "No data".
When inserting an element into an array, we moved the elements with larger index values, starting at the end of the array. Why is it wrong to start at the insertion location, like this? for (int i = pos; i < currentSize - 1; i++) { values[i + 1] = values[i]; }
This loop sets all elements to values[pos].
When using a String object, you do not know how it stores its characters. How can you access them?
Through the substring and charAt methods.
Maximum and Minimum (Loop)
To compute the largest value in a sequence, keep a variable that stores the largest element that you have encountered, and update it when you find a larger one. double largest = in.nextDouble(); while (in.hasNextDouble()) { double input = in.nextDouble(); if (input > largest) { largest = input; } } This algorithm requires that there is at least one input. To compute the smallest value, simply reverse the comparison: double smallest = in.nextDouble(); while (in.hasNextDouble()) { double input = in.nextDouble(); if (input < smallest) { smallest = input; } } image
Use arrays for collecting values.
Use arrays for collecting values. image © Luckie8/iStockphoto • An array collects a sequence of values of the same type. • Individual elements in an array are accessed by an integer index i, using the notation array[i]. • An array element can be used like any variable. • An array index must be at least zero and less than the size of the array. • A bounds error, which occurs if you supply an invalid array index, can cause your program to terminate. • Use the expression array.length to find the number of elements in an array. • An array reference specifies the location of an array. Copying the reference yields a second reference to the same array. • With a partially filled array, keep a companion variable for the current size. Know and use common array algorithms. image © yekorzh/iStockphoto • When separating elements, don't place a separator before the first element. • A linear search inspects elements in sequence until a match is found. • Before inserting an element, move elements to the end of the array starting with the last one. • Use a temporary variable when swapping two elements. • Use the Arrays.copyOf method to copy the elements of an array into a new array. • Arrays can occur as method arguments and return values. • By combining fundamental algorithms, you can solve complex programming tasks. • You should be familiar with the implementation of fundamental algorithms so that you can adapt them. • Use a sequence of coins, playing cards, or toys to visualize an array of values. • You can use paper clips as position markers or counters. • Use a two-dimensional array to store tabular data. • Individual elements in a two-dimensional array are accessed by using two index values, array[i][j]. Use array lists for managing collections whose size can change. image © digital94086/iStockphoto • An array list stores a sequence of values whose size can change. • The ArrayList class is a generic class: ArrayList<Type> collects elements of the specified type. • Use the size method to obtain the current size of an array list. • Use the get and set methods to access an array list element at a given index. • Use the add and remove methods to add and remove array list elements. • To collect numbers in array lists, you must use wrapper classes.
It is possible to determine the answer to Self Check 3 without knowing how the Math.ceil method is implemented. Use an engineering term to describe this aspect of the Math.ceil method.
Users of the method can treat it as a black box.
Why does the loop body in Dice.java call Math.random() twice?
We need to call it once for each die. If we printed the same value twice, the die tosses would not be independent.
Comparing Adjacent Values (Loop)
When processing a sequence of values in a loop, you sometimes need to compare a value with the value that just preceded it. For example, suppose you want to check whether a sequence of inputs contains adjacent duplicates such as 1 7 2 9 9 4 9. Now you face a challenge. Consider the typical loop for reading a value: double input; while (in.hasNextDouble()) { input = in.nextDouble(); . . . } How can you compare the current input with the preceding one? At any time, input contains the current input, overwriting the previous one. The answer is to store the previous input, like this: double input = 0; while (in.hasNextDouble()) { double previous = input; input = in.nextDouble(); if (input = = previous) { System.out.println("Duplicate input"); } } One problem remains. When the loop is entered for the first time, input has not yet been read. You can solve this problem with an initial input operation outside the loop: double input = in.nextDouble(); while (in.hasNextDouble()) { double previous = input; input = in.nextDouble(); if (input = = previous) { System.out.println("Duplicate input"); } }
What happens when you supply the same name for the input and output files to the Total program? Try it out if you are not sure.
When the PrintWriter object is created, the output file is emptied. Sadly, that is the same file as the input file. The input file is now empty and the while loop exits immediately.
declaring a method
When writing this method, you need to • Pick a name for the method (cubeVolume). • Declare a variable for each argument (double sideLength). These variables are called the parameter variables. • Specify the type of the return value (double). • Add the public static modifiers. We will discuss the meanings of these modifiers in Chapter 8. For now, you should simply add them to your methods. Put all this information together to form the first line of the method's declaration: public static double cubeVolume(double sideLength) This line is called the header of the method. Next, specify the body of the method. The body contains the variable declarations and statements that are executed when the method is called.
Suppose Java didn't have a do loop. Could you rewrite any do loop as a while loop?
Yes. The do loop do { body } while (condition); is equivalent to this while loop: boolean first = true; while (first || condition) { body; first = false; }
How do you get the first character of a string? The last character? How do you remove the first character? The last character?
You can read characters from a string with the charAt method. For the first character, pass a position of 0 to charAt. For the last character pass the position that is equal to the length of the string -1 to charAt. Strings in Java are immutable, so they cannot be directly changed. Thus, to "remove" the first character from a string, we can take a substring of the original string that contains the entire thing minus the first character. If our string is called s, then this works: s.substring(1, s.length());. The last character can be obtained by extracting the substring that contains the entire string minus the last character, like this: s.substring(0, s.length()-1);.
Hand-trace the following code, assuming that a is 2 and n is 4. Then explain what the code does for arbitrary values of a and n. int r = 1; int i = 1; while (i <= n) { r = r * a; i++; }
a n r i 2 4 1 1 2 2 4 3 8 4 16 5
Which of the following conditions are true, provided a is 3 and b is 4? a. a + 1 <= b Answer b. a + 1 >= b Answer c. a + 1 != b
a + 1 <= b Answer: True
What are the values of the following expressions? In each line, assume that double x = 2.5; double y = -1.5; int m = 18; int n = 4; a) x + n * y - (x + n) * y b) m / n + m % n c) 5 * x - n / 5 d) 1 - (1 - (1 - (1 - (1 - n)))) e) Math.sqrt(Math.sqrt(n))
a) 6.25 b) 6 c) 12.5 d) -3 e) 1.4142135623730951
Give examples of the following methods from the Java library. a) A method with a double argument and a double return value b) A method with two double arguments and a double return value c) A method with a String argument and a double return value d) A method with no arguments and a double return value
a) Math.sqrt(x) b) Math.pow(x, y) c) Double.parseDouble(x) d) Math.random()
Comments
are enclosed in /** and */ delimiters.
Arguments
are supplied when a method is called.
How do you generate the following printout, using the boxString method? ------- !Hello! ------- ------- !World! -------
boxString("Hello"); boxString("World");
The following pseudocode is intended to count the number of digits in the number n: count = 1 temp = n while (temp > 10) Increment count. Divide temp by 10.0. Trace the pseudocode for n and n . What error do you find?
count temp 1 123 2 12.3 3 1.23 This yields the correct answer. The number 123 has 3 digits. count temp 1 100 2 10 This yields the wrong answer. The number 100 also has 3 digits. The loop condition should have been while (temp >= 10)
A sentinel value
denotes the end of a data set, but it is not part of the data.
Suppose that we want to check for inputs that are at least 0 and at most 100. Modify the do loop for this check.
do { System.out.print( "Enter a value between 0 and 100: "); value = in.nextInt(); } while (value < 0 || value > 100);
How do you compute the total of all positive inputs?
double total = 0; while (in.hasNextDouble()) { double input = in.nextDouble(); if (input > 0) { total = total + input; } }
Give the opposite of the condition floor > 13
floor <= 13
When printing separators, we skipped the separator before the initial element. Rewrite the loop so that the separator is printed after each element, except for the last element.
for (int i = 0; i < values.length; i++) { System.out.print(values[i]); if (i < values.length - 1) { System.out.print(" | "); } } Now you know why we set up the loop the other way.
Write a for loop that prints all even numbers between 10 and 20 (inclusive).
for (int i = 10; i <= 20; i = i + 2) { System.out.println(i); }
Write nested loops that make the following pattern of brackets: [][][][] [][][][] [][][][]
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 4; j++) { System.out.print("[]"); } System.out.println(); }
How would you modify the for loop of the InvestmentTable.java program to print all balances until the investment has doubled?
for (int year = 1; balance <= 2 * INITIAL_BALANCE; year++) However, it is best not to use a for loop in this case because the loop condition does not relate to the year variable. A while loop would be a better choice.
black box
for a device with a given specification but unknown implementation.
Consider this method that prints a page number on the left or right side of a page: if (page % 2 = = 0) { System.out.println(page); } else { System.out.println(" " + page); } Introduce a method with return type boolean to make the condition in the if statement easier to understand.
if (isEven(page)) . . . where the method is defined as follows: public static boolean isEven(int n) { return n % 2 = = 0; }
In a game program, the scores of players A and B are stored in variables scoreA and scoreB. Assuming that the player with the larger score wins, write an if/else if/else sequence that prints out "A won", "B won", or "Game tied".
if (scoreA > scoreB) { System.out.println("A won"); } else if (scoreA < scoreB) { System.out.println("B won"); } else { System.out.println("Game tied"); }
Write a conditional statement with three branches that sets s to 1 if x is positive, to −1 if x is negative, and to 0 if x is zero.
if (x > 0) { s = 1; } else if (x < 0) { s = -1; } else { s = 0; }
Supply a condition in this if statement to test whether the user entered a Y: System.out.println("Enter Y to quit."); String input = in.next(); if (. . .) { System.out.println("Goodbye."); }
input.equals("Y")
Write a loop that counts how many elements in an array are equal to zero.
int count = 0; for (double x : values) { if (x = = 0) { count++; } }
The comment explains what the following loop does. Use a method instead. // Counts the number of spaces int spaces = 0; for (int i = 0; i < input.length(); i++) { if (input.charAt(i) = = ' ') { spaces++; } } In Self Check 24, you were asked to implement a method that counts spaces. How can you generalize it so that it can count any character? Why would you want to do this?
int spaces = countSpaces(input); where the method is defined as follows: /** @param str any string @return the number of spaces in str */ public static int countSpaces(String str) { int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) = = ' ') { count++; } } return count; } ---------------------------- It is very easy to replace the space with any character. /** @param str any string @param ch a character whose occurrences should be counted @return the number of times that ch occurs in str */ public static int count(String str, char ch) { int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) = = ch) { count++; } } return count; } This is useful if you want to count other characters. For example, count(input, ",") counts the commas in the input.
Write a for loop that computes the sum of the integers from 1 to n.
int sum = 0; for (int i = 1; i <= n; i++) { sum = sum + i; }
Consider the following statements: int totalPennies = (int) Math.round(100 * total) % 100; int taxPennies = (int) Math.round(100 * (total * taxRate)) % 100; Introduce a method to reduce code duplication.
int totalPennies = getPennies(total); int taxPennies = getPennies(total * taxRate); where the method is defined as /** @param amount an amount in dollars and cents @return the number of pennies in the amount */ public static int getPennies(double amount) { return (int) Math.round(100 * amount) % 100; }
Rewrite the input check do loop using a while loop. What is the disadvantage of your solution?
int value = 100; while (value >= 100) { System.out.print("Enter a value < 100: "); value = in.nextInt(); } Here, the variable value had to be initialized with an artificial value to ensure that the loop is entered at least once.
Write a do loop that reads integers and computes their sum. Stop when reading the same value twice in a row. For example, if the input is 1 2 3 4 4, then the sum is 14 and the loop stops.
int x = 0; int previous; do { previous = x; x = in.nextInt(); sum = sum + x; } while (x != 0 && previous != x);
Write a do loop that reads integers and computes their sum. Stop when reading the value 0.
int x; int sum = 0; do { x = in.nextInt(); sum = sum + x; } while (x != 0);
Write the for loop of the InvestmentTable.java program as a while loop.
int year = 1; while (year <= nyears) { double interest = balance * RATE / 100; balance = balance + interest; System.out.printf("%4d %10.2f\n", year, balance); year++; }
How do you call the squares method to compute the first five squares and store the result in an array numbers?
int[] numbers = squares(5);
Declare an array of integers containing the first five prime numbers. Assume the array primes has been initialized as described in Self Check 1. What does it contain after executing the following loop?
int[] primes = { 2, 3, 5, 7, 11 }; 2, 3, 5, 3, 2
A method
is a named sequence of instructions When declaring a method, you provide a name for the method, a variable for each argument, and a type for the result. Method comments explain the purpose of the method, the meaning of the parameter variables and return value, as well as any special requirements. Eliminate replicated code or pseudocode by defining a method.
The return value
is the result that the method computes.
Trace the following code. What error do you observe? int n = 1; while (n != 50) { System.out.println(n); n = n + 10; }
n output 1 1 11 11 21 21 31 31 41 41 51 51 61 61 ...
Hand-trace the following code, showing the value of n and the output. What potential error do you notice? int n = 1; while (n <= 3) { System.out.print(n + ", "); n++; }
n output 1 1, 2 1, 2, 3 1, 2, 3, 4
Hand-trace the following code, showing the value of n and the output. int n = 5; while (n >= 0) { n--; System.out.print(n); }
n output 5 4 4 3 3 2 2 1 1 0 0 −1 −1
Complete the following truth table by finding the truth values of the Boolean expressions for all combinations of the Boolean inputs p, q, and r. p q r (p && q) || !r !(p && (q || !r)) false false false false false true false true false ... 5 more combinations ...
p q r (p && q) || !r !(p && (q || !r)) false false false true true false false true false true false true false true true false true true false true true false false true false true false true false true true true false true false true true true true false
uppose you wanted to add the total to an existing file instead of writing a new file. Self Check 1 indicates that you cannot simply do this by specifying the same file for input and output. How can you achieve this task? Provide the pseudocode for the solution.
pen a scanner for the file. For each number in the scanner Add the number to an array. Close the scanner. Set total to 0. Open a print writer for the file. For each number in the array Write the number to the print writer. Add the number to total. Write total to the print writer. Close the print writer.
Write a program that displays your name inside a box on the screen, like this: Do your best to approximate lines with characters such as | - +.
public class NameInABox { public static void main(String[] args) { System.out.println("+------+"); System.out.println("| Dave |"); System.out.println("+------+"); } }
Write a program that prints a multiplication table, like this:
public class PrintMultiplicationTable { public static void main(String[] args) { int maxDigit = 10; for (int i = 1; i <= maxDigit; i++) { for (int j = 1; j <= maxDigit; j++) { System.out.printf("%4d", i * j); } System.out.println(); } } }
Declare a method squareArea that computes the area of a square of a given side length.
public static double squareArea( double sideLength) { double area = sideLength * sideLength; return area; }
How would you modify the boxString method to leave a space around the string that is being boxed, like this: --------- ! Hello ! ---------
public static void boxString(String contents) { int n = contents.length(); for (int i = 0; i < n + 4; i++) { System.out.print("-"); } System.out.println(); System.out.println("! " + contents + " !"); for (int i = 0; i < n + 4; i++) { System.out.print("-"); } System.out.println() }
Write a method fill that fills all elements of an array of integers with a given value. For example, the call fill(scores, 10) should fill all elements of the array scores with the value 10.
public static void fill(int[] values, int value) { for (int i = 0; i < values.length; i++) { values[i] = value; } }
The boxString method contains the code for printing a line of - characters twice. Place that code into a separate method printLine, and use that method to simplify boxString. What is the code of both methods?
public static void printLine(int count) { for (int i = 0; i < count; i++) { System.out.print("-"); } System.out.println(); } public static void boxString(String contents) { int n = contents.length(); printLine(n + 2); System.out.println("!" + contents + "!"); printLine(n + 2); }
Implement a method shout that prints a line consisting of a string followed by three exclamation marks. For example, shout("Hello") should print Hello!!!. The method should not return a value.
public static void shout(String message) { System.out.println(message ++ "!!!"); }
How could you achieve the task of Self Check 12 with only two branches?
s = 0; if (x > 0) { s = 1; } else if (x < 0) { s = -1; }
How do you test that a string str is the empty string?
str.equals("") or str.length() == 0
The return statement
terminates a method call and yields the method result.
What is the error in this statement? if (scoreA = scoreB) { System.out.println("Tie"); }
the values should be compared with ==, not =.
Suppose x and y are two integers. How do you test whether both of them are zero?
x == 0 && y == 0
How do you test whether at least one of them is zero?
x == 0 || y == 0
recursive method
• A recursive computation solves a problem by using the solution of the same problem with simpler inputs. • For a recursion to terminate, there must be special cases for the simplest inputs. • The key to finding a recursive solution is reducing the input to a simpler input for the same problem. • When designing a recursive solution, do not worry about multiple nested calls. Simply focus on reducing a problem to a slightly simpler one.
Declare variables with appropriate names and types.
• A variable is a storage location with a name. • When declaring a variable, you usually specify an initial value. • When declaring a variable, you also specify the type of its values. • Use the int type for numbers that cannot have a fractional part. • Use the double type for floating-point numbers. • By convention, variable names should start with a lowercase letter. • An assignment statement stores a new value in a variable, replacing the previously stored value. • The assignment operator = does not denote mathematical equality. • You cannot change the value of a variable that is defined as final. • Use comments to add explanations for humans who read your code. The compiler ignores comments.
Write programs that read user input and print formatted output.
• Java classes are grouped into packages. Use the import statement to use classes from packages. • Use the Scanner class to read keyboard input in a console window. • Use the printf method to specify how values should be Formated • The API (Application Programming Interface) documentation lists the classes and methods of the Java library.
Write arithmetic expressions in Java.
• Mixing integers and floating-point values in an arithmetic expression yields a floating-point value. • The ++ operator adds 1 to a variable; the −− operator subtracts 1. • If both arguments of / are integers, the remainder is discarded. • The % operator computes the remainder of an integer division. • The Java library declares many mathematical functions, such as Math.sqrt (square root) and Math.pow (raising to a power). • You use a cast (typeName) to convert a value to a different type.
Write programs that process strings.
• Strings are sequences of characters. • The length method yields the number of characters in a string. • Use the + operator to concatenate strings; that is, to put them together to yield a longer string. • Whenever one of the arguments of the + operator is a string, the other argument is converted to a string. • Use the next method of the Scanner class to read a string containing a single word. • String positions are counted starting with 0. • Use the substring method to extract a part of a string.
Loops
• The for loop is used when a value runs from a starting point to an ending point with a constant increment or decrement. • The do loop is appropriate when the loop body must be executed at least once. • You can use a Boolean variable to control a loop. Set the variable to true before entering the loop, then set it to false to leave the loop. • Use input redirection to read input from a file. Use output redirection to capture program output in a file. • When the body of a loop contains another loop, the loops are nested. A typical use of nested loops is printing a table with rows and columns.
This chapter contains a number of recommendations regarding variables and constants that make programs easier to read and maintain. Briefly summarize these recommendations.
• Variable names are in lowercase with occasional uppercase characters in the middle. • Constant names are in uppercase with the occasional underscore. • No magic numbers may be used.
In order to estimate the cost of painting a house, a painter needs to know the surface area of the exterior. Develop an algorithm for computing that value. Your inputs are the width, length, and height of the house, the number of windows and doors, and their dimensions. (Assume the windows and doors have a uniform size.)
// Inputs are width, length, height, number of windows, number of doors, // window width, window height, door width, door height surface area of side 1 = width * height surface area of side 2 = length * height surface area of doors = door width * door height * number of doors surface area of windows = window width * window height * number of windows surface area without doors or windows = (surface area of side 1) * 2 + (surface area of side 2) * 2 // This is what we want to know: total surface area = surface area without doors or windows - (surface area of doors + surface area of windows)
The Two Categories of Errors:
1) Compile-time Errors Syntax Errors Spelling, Capitalization, punctuation Ordering of statements, matching of braces/parenthesis... No .class file is generated by the compiler Correct first error listed, then compile again 2) Run-time Errors Logic Errors Program runs, but produces unintended results Program may 'crash'
Find three run-time errors in the following program. public class HasErrors { public static void main(String[] args) { int x = 0; int y = 0; Scanner in = new Scanner("System.in"); System.out.print("Please enter an integer:"); x = in.readInt(); System.out.print("Please enter another integer: "); x = in.readInt(); System.out.println("The sum is " + x + y); } }
1) The scanner should have been constructed as Scanner in = new Scanner(System.in); 2) The second integer should have been read as y = in.readInt(); 3) The sum should have been printed as "The sum is " + (x + y), so that the integer x is not concatenated with the string "The sum is".
Explain the difference between s = 0; if (x > 0) { s++; } if (y > 0) { s++; } and s = 0; if (x > 0) { s++; } else if (y > 0) { s++; }
In the first block, the conditions are evaluated sequentially, so s could be incremented twice. In the second block, the conditional statements are mutually exclusive, so, s cannot be incremented more than once.
What does this program print? public class Test { public static void main(String[] args) { System.out.println("39 + 3"); System.out.println(39 + 3); } }
The program prints the following: 39 + 3 42 Java interprets the statement "39 + 3" as a string and thus prints out the literal characters 39 + 3. Java interprets the second statement 39 + 3 as an operation between two numbers, so it first calculates the value 39 + 3 = 42 then prints out the result 42.
Concatenation
When the expression to the left or the right of a + operator is a string, the other one is automatically forced to become a string as well, and both strings are concatenated. For example, consider this code: String jobTitle = "Agent"; int employeeId = 7; String bond = jobTitle + employeeId;
Provide trace tables for these loops. a. int i = 0; int j = 10; int n = 0; while (i j) { i++; j--; n++; } b. int i = 0; int j = 0; int n = 0; while (i 10) { i++; n = n + i + j; j++; } c. int i = 10; int j = 0; int n = 0; while (i > 0) { i--; j++; n = n + i - j; } d. int i = 0; int j = 10; int n = 0; while (i != j) { i = i + 2; j = j - 2; n++; }
a) b) c) d) As the trace table shows, i will never equal j since they pass each other at the 4-6 to 6-4 mark. The trace table stops right below this point to indicate it is an infinite loop.
Write method headers for methods with the following descriptions. a) Computing the larger of two integers b) Computing the smallest of three floating-point numbers c) Checking whether an integer is a prime number, returning true if it is and false otherwise d) Checking whether a string is contained inside another string e) Computing the balance of an account with a given initial balance, an annual interest rate, and a number of years of earning interest f) Printing the balance of an account with a given initial balance and an annual interest rate over a given number of years g) Printing the calendar for a given month and year h) Computing the weekday for a given day, month, and year (as a string such as "Monday") i) Generating a random integer between 1 and n
a) /** Computes the larger of two integers. @param a first integer @param b second integer @return the larger of a and b */ public static int larger(int a, int b) b) /** Computes the smallest of three floating-point numbers. @param a first number @param b second number @param c third number @return the smallest of a, b, and c */ public static double smallest(double a, double b, double c) c) /** Checks whether an integer is a prime number. @param x number to test @return true if x is prime, otherwise false */ public static boolean isPrime(int x) d) /** Checks to see whether a string is contained inside another string. @param mainString the base string @param possibleInside the string to check to see if it's inside mainString @return true if possibleInside is inside mainString, false otherwise */ public static boolean containedInside(String mainString, String possibleInside) e) /** Computes the balance of an account with a given annual balance, an annual interest rate, and a number of years of earning interest, @param initialBalance initial balance of account @param annualInterestRate the annual interest rate @param numberOfYears number of years earning interest @return the balance of the account after numberOfYears past */ public static double computeBalance(double initialBalance, double annualInterestRate, int numberOfYears) f) /** Prints the balance of an account with a given annual balance, an annual interest rate, and a number of years of earning interest. @param initialBalance initial balance of account @param annualInterestRate the annual interest rate @param numberOfYears number of years earning interest @return the balance of the account after numberOfYears past */ public static void printBalance(double initialBalance, double annualInterestRate, int numberOfYears) g) /** Prints the calendar for a given month and year. @param month numerical value of month @param year numerical value of year */ public static void printCalendar(int month, int year) h) /** Computes the weekday for a given day, month and year. @param day numerical value of day @param month numerical value of month @param year numerical value of year @return the day of the week */ public static String computeWeekDay(int day, int month, int year) i) /** Generates a random integer between 1 and n @param n upper bound of random number @return a random number between 1 and n */ public int generateRandomNumber(int n)
Write a loop that computes a. The sum of all even numbers between 2 and 100 (inclusive). b. The sum of all squares between 1 and 100 (inclusive). c. The sum of all odd numbers between a and b (inclusive). d. The sum of all odd digits of n. (For example, if n is 32677, the sum would be 3 + 7 + 7 = 17.)
a) int sumOfEvenNumbers = 0; for (int n <= 2; n = 100; n = n + 2) { sumOfEvenNumbers = sumOfEvenNumbers + n; } // sumOfEvenNumbers now has the sum of all even numbers from 2 to 100 b) int sumOfSquares = 0; int currentN = 1; while (Math.pow(currentN, 2) <= 100) { sumOfSquares = sumOfSquares + Math.pow(currentN, 2); currentN++; } // sumOfSquares now has the sum of all squares from 1 to 100 c) int sumOfOddNumbers = 0; for (int n = a; n <= b; n++) { if (n % 2 == 1) { sumOfOddNumbers = sumOfOddNumbers + n; } } //sumOfOddNumbers now has the value of all odd numbers between a and b d) int nLeft = n; int sumOfOddDigits = 0; while (nLeft > 0) { int digit = nLeft % 10; if (digit % 2 == 1) { sumOfOddDigits = sumOfOddDigits + digit; } nLeft = nLeft / 10; } // sumOfOddNumbers now has sum of all odd digits in n
Write the following methods and provide a program to test them. a) double smallest(double x, double y, double z), returning the smallest of the arguments b) double average(double x, double y, double z), returning the average of the arguments
a) public double smallest(double x, double y, double z), returning the smallest of the arguments import java.util.Scanner; public class Smallest { /** Returns the smallest of the three arguments. @param x the first number @param y the second number @param z the third number @return a double which is the smallest of the three params */ public static double smallest(double x, double y, double z) { if (x <= y && x <= z) { return x; } else if (y <= x && y <= z) { return y; } else { return z; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter three numbers: "); double a = in.nextDouble(); double b = in.nextDouble(); double c = in.nextDouble(); System.out.println("The smallest number is: " + smallest(a, b, c)); } } b) public double average(double x, double y, double z), returning the average of the arguments import java.util.Scanner; public class Average { /** Returns the average of the three arguments. @param x the first number @param y the second number @param z the third number @return a double which is the average of the three */ public static double average(double x, double y, double z) { return (x + y + z) / 3.0; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter three numbers: "); double a = in.nextDouble(); double b = in.nextDouble(); double c = in.nextDouble(); System.out.println("The average of the numbers is: " + average(a, b, c)); } }
What do these loops print? a. for (int i = 1; i 10; i++) { System.out.print(i + " "); } b. for (int i = 1; i 10; i += 2) { System.out.print(i + " "); } c. for (int i = 10; i > 1; i--) { System.out.print(i + " "); } d. for (int i = 0; i 10; i++) { System.out.print(i + " "); } e. for (int i = 1; i 10; i = i * 2) { System.out.print(i + " "); } f. for (int i = 1; i 10; i++) { if (i % 2 == 0) { System.out.print(i + " "); } }
a) 1 2 3 4 5 6 7 8 9 b) 1 3 5 7 9 c) 10 9 8 7 6 5 4 3 2 d) 0 1 2 3 4 5 6 7 8 9 e) 1 2 4 8 f) 2 4 6 8
True or false? a) A method has exactly one return statement. b) A method has at least one return statement. c) A method has at most one return value. d) A method with return value void never has a return statement. e) When executing a return statement, the method exits immediately. f) A method with return value void must print a result. g) A method without parameter variables always returns the same value.
a) False b) False c) True d) False e) True f) False g) False
Write programs that read a line of input as a string and print a. Only the uppercase letters in the string. b. Every second letter of the string. c. The string, with all vowels replaced by an underscore. d. The number of vowels in the string. e. The positions of all vowels in the string.
a) Only the uppercase letters. (Note: Later in the textbook, we will learn how to read a line of text that includes spaces, but for now we are limited to text strings with no spaces, because the Scanner.next method stops reading when it encounters a space.) import java.util.Scanner; public class OnlyUppercaseLetters { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); for (int n = 0; n < word.length(); n++) { // Find out if letter is uppercase or not. char ch = word.charAt(n); if (ch == 'A' || ch == 'B' || ch == 'C' || ch == 'D' || ch == 'E' || ch == 'F' || ch == 'G' || ch == 'H' || ch == 'I' || ch == 'J' || ch == 'K' || ch == 'L' || ch == 'M' || ch == 'N' || ch == 'O' || ch == 'P' || ch == 'Q' || ch == 'R' || ch == 'S' || ch == 'T' || ch == 'U' || ch == 'V' || ch == 'W' || ch == 'X' || ch == 'Y' || ch == 'Z') { System.out.print(ch); } } } } b) Every second letter of the string. import java.util.Scanner; public class SecondLetterString { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); for (int n = 0; n < word.length(); n++) { // Print only if n is odd (which is every second letter) char ch = word.charAt(n); if (n % 2 == 1) // odd { System.out.print(ch); } } } } c) The string with vowels replaced by an underscore. import java.util.Scanner; public class VowelsReplacedUnderscore { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); for (int n = 0; n < word.length(); n++) { // Check each letter to see if a vowel, // and if it is, replace it with an underscore char ch = word.charAt(n); if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') { System.out.print('_'); } else { System.out.print(ch); } } } } d) The number of vowels in the string. import java.util.Scanner; public class NumberofVowels { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); int numVowels = 0; for (int n = 0; n < word.length(); n++) { // Check each letter to see if a vowel, // and increment counter char ch = word.charAt(n); if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') { numVowels++; } } System.out.print("Number of vowels: " + numVowels); } } e) The position of the vowels in the string. import java.util.Scanner; public class PositionVowels { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); System.out.print("Vowels in positions: "); for (int n = 0; n < word.length(); n++) { // Check each letter to see if a vowel, // and print its position char ch = word.charAt(n); if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') { System.out.print(n + " "); } } } }
Write programs that read a sequence of integer inputs and print a. The smallest and largest of the inputs. b. The number of even and odd inputs. c. Cumulative totals. For example, if the input is 1 7 2 9, the program should print 1 8 10 19. d. All adjacent duplicates. For example, if the input is 1 3 3 4 5 5 6 6 2, the program should print 3 5 6.
a) Smallest and largest of the inputs import java.util.Scanner; public class LargestInput { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a series of numbers, then type Q to process: "); int largest; largest = in.nextInt(); int smallest = largest; int input; // Loop on input and check for a new min or max while (in.hasNextInt()) { input = in.nextInt(); if (input > largest) { largest = input; } if (input < smallest) { smallest = input; } } // Output the results System.out.print("Largest: " + largest + "\n" + "Smallest: " + smallest); } } b) Number of even and odd inputs import java.util.Scanner; public class NumberEvenOddInputs { public static void main(String[] args) { int numOdd = 0; int numEven = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a series of numbers, then type Q to process: "); int input; // Loop on input and check oddness or evenness while (in.hasNextInt()) { input = in.nextInt(); if (input % 2 == 0) // even { numEven++; } else // odd { numOdd++; } } // Print the results System.out.println("Number of even: " + numEven + "\n" + "Number of odd: " + numOdd); } } c) Cumulative totals import java.util.Scanner; public class CummulativeTotals { public static void main(String[] args) { double sum = 0.0; Scanner in = new Scanner(System.in); System.out.print("Enter a series of numbers, then type Q to process: "); double input; // Calculate and print cumulative totals while (in.hasNextDouble()) { input = in.nextDouble(); sum = sum + input; System.out.print(sum + " "); } } } d) All adjacent duplicates import java.util.Scanner; public class AdjacentDuplicates { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print( "Enter a series of numbers, then type Q to process: "); int input; int previous; previous = in.nextInt(); // Find and print adjacent duplicates while (in.hasNextInt()) { input = in.nextInt(); if (input == previous) { System.out.print(input + " "); } previous = input; } } }
Write programs with loops that compute a. The sum of all even numbers between 2 and 100 (inclusive). b. The sum of all squares between 1 and 100 (inclusive). c. All powers of 2 from 20 up to 220. d. The sum of all odd numbers between a and b (inclusive), where a and b are inputs. e. The sum of all odd digits of an input. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)
a) Sum of all even numbers between 2 and 100 public class SumEvenNumbers { public static void main(String[] args) { int sum = 0; // The sum of all even numbers between 2 and 100 for (int x = 2; x <= 100; x = x + 2) { sum = sum + x; } // Output the result System.out.println("The sum is " + sum); } } b) Sum of all squares between 1 and 100 public class SumSquares { public static void main(String[] args) { int sum = 0; // The sum of all squares between 1 and 100 for (int x = 1; x <= 100; x++) { sum = sum + x * x; } // Output the result System.out.println("The sum is " + sum); } } c) The powers of 2 from 20 up to 220 public class Powerof2 { public static void main(String[] args) { // The powers of 2 from 2^0 to 2^20 for (int x = 0; x <= 20; x++) { System.out.println( "2 to the " + x + " equals " + Math.pow(2.0, x)); } } } d) Sum of all odd numbers between a and b (which are inputs) import java.util.Scanner; public class SumOfOddNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Get the inputs System.out.print("Enter a: "); int a; a = in.nextInt(); System.out.print("Enter b: "); int b; b = in.nextInt(); int sum = 0; // The sum of odd numbers between a and b for (int x = a; x <= b; x++) { // Only add number if it is odd if (x % 2 == 1) { sum = sum + x; } } // Output the result System.out.println("The sum is " + sum + "."); } e) Sum of all odd digits of an input import java.util.Scanner; public class SumOfOddDigits { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Get the input System.out.print("Enter an integer number: "); int num; num = in.nextInt(); int sum = 0; int digit; // The sum of odd digits of the input while (num > 0) { digit = num % 10; // Only add digit if it is odd if (digit % 2 == 1) { sum = sum + digit; } num = num / 10; } // Output the result System.out.print("The sum is " + sum + "."); } }
Find the errors in the following if statements. a) if x > 0 then System.out.print(x); b) if (1 + x > Math.pow(x, Math.sqrt(2)) { y = y + x; } c) if (x = 1) { y++; } d) x = in.nextInt(); if (in.hasNextInt()) { sum = sum + x; } else { System.out.println("Bad input for x"); } e) String letterGrade = "F"; if (grade >= 90) { letterGrade = "A"; } if (grade >= 80) { letterGrade = "B"; } if (grade >= 70) { letterGrade = "C"; } if (grade >= 60) { letterGrade = "D"; }
a) There are two errors in this code. First, there are no parentheses around the x > 0 part of the if statement. Secondly, there is an extraneous then which is not part of the Java syntax, instead we should wrap the body of the if statement in curly braces. A correct form would be: if (x > 0) { System.out.print(x); } b) In this statement there aren't enough parentheses to balance the condition (there are only two). The following would be correct: if (1 + x > Math.pow(x, Math.sqrt(2))) { y = y + x; } c) In this case there is only a single = in the if statement. Likely the programmer wanted to check for equality rather than set x equal to the value of 1. A correct form would be: if (x == 1) { y++; } d) The problem in this case is that the programmer tried to validate the input after she read it thus defeating the whole purpose of input validation. Instead we should take the line which reads the integer into the body of the if statement, like this: if (in.hasNextInt()) { x = in.nextInt(); sum = sum + x; } else { System.out.println("Bad input for x"); e) The if statements should be an if/else if/else sequence. More than one if statement will be executed for any grade higher than 60 and the letter grade will be wrongly assigned.
Write an algorithm to settle the following question: A bank account starts out with $10,000. Interest is compounded monthly at 6 percent per year (0.5 percent per month). Every month, $500 is withdrawn to meet college expenses. After how many years is the account depleted?
balance = $10,000 total months = 0 while balance is greater than $0 increase balance by 0.5% of its value decrease balance by $500 add 1 to the total number of months years to deplete = total months / 12
The following algorithm yields the season (Spring, Summer, Fall, or Winter) for a given month and day. If month is 1, 2, or 3, season = "Winter" Else if month is 4, 5, or 6, season = "Spring" Else if month is 7, 8, or 9, season = "Summer" Else if month is 10, 11, or 12, season = "Fall" If month is divisible by 3 and day >= 21 If season is "Winter", season = "Spring" Else if season is "Spring", season = "Summer" Else if season is "Summer", season = "Fall" Else season = "Winter" Write a program that prompts the user for a month and day and then prints the season, as determined by this algorithm.
import java.util.Scanner; public class Season { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a month and day: "); int month = in.nextInt(); int day = in.nextInt(); String season = ""; if (month <= 3) { season = "Winter"; } else if (month <= 6) { season = "Spring"; } else if (month <= 9) { season = "Summer"; } else { season = "Fall"; } if (month % 3 == 0 && day >= 21) { if (season.compareTo("Winter") == 0) { season = "Spring"; } else if (season.compareTo("Spring") == 0) { season = "Summer"; } else if (season.compareTo("Summer") == 0) { season = "Fall"; } else { season = "Winter"; } } System.out.println(season); } }
Write the following methods and provide a program to test them. a) boolean allTheSame(double x, double y, double z), returning true if the arguments are all the same b) boolean allDifferent(double x, double y, double z), returning true if the arguments are all different c) boolean sorted(double x, double y, double z), returning true if the arguments are sorted, with the smallest one coming first
import java.util.Scanner; public class BoolTest { /** Determines if the three arguments are all equal. @param x the first number @param y the second number @param z the third number @return true if all the same, otherwise false */ public static boolean allTheSame(double x, double y, double z) { if (x == y && y == z) { return true; } else { return false; } } /** Determines if the three arguments are all NOT equal. @param x the first number @param y the second number @param z the third number @return true if all different, otherwise false */ public static boolean allDifferent(double x, double y, double z) { if (x != y && y != z && x != z) { return true; } else { return false; } } /** Determines if the three arguments are in order, smallest first. @param x the first number @param y the second number @param z the third number @return true if in order, otherwise false */ public static boolean sorted(double x, double y, double z) { if (x <= y && y <= z) { return true; } else { return false; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter three numbers: "); double a = in.nextDouble(); double b = in.nextDouble(); double c = in.nextDouble(); if (allTheSame(a, b, c)) { System.out.println("All the same!"); } if (allDifferent(a, b, c)) { System.out.println("All different!"); } if (sorted(a, b, c)) { System.out.println("Those darned numbers are sorted!"); } } }
The original U.S. income tax of 1913 was quite simple. The tax was • 1 percent on the first $50,000. • 2 percent on the amount over $50,000 up to $75,000. • 3 percent on the amount over $75,000 up to $100,000. • 4 percent on the amount over $100,000 up to $250,000. • 5 percent on the amount over $250,000 up to $500,000. • 6 percent on the amount over $500,000. There was no separate schedule for single or married taxpayers. Write a program that computes the income tax according to this schedule.
import java.util.Scanner; public class Calculate1913Tax { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter your income:"); double income = in.nextDouble(); final double PERCENT_PER_STEP = 0.01; double tax = income * PERCENT_PER_STEP; if (income > 50000) { tax += (income-50000) * PERCENT_PER_STEP; } if (income > 75000) { tax += (income - 75000) * PERCENT_PER_STEP; } if (income > 100000) { tax += (income - 100000) * PERCENT_PER_STEP; } if (income > 250000) { tax += (income - 250000) * PERCENT_PER_STEP; } if (income > 500000) { tax += (income - 500000) * PERCENT_PER_STEP; } System.out.printf("You owe $%.2f in tax.\n", tax); } }
Write a program that prompts the user for a measurement in meters and then converts it to miles, feet, and inches.
import java.util.Scanner; public class ConvertMeasurements { public static void main(String[] args) { final double METERS_PER_MILE = 1609.344; final double METERS_PER_FEET = 0.3048; final double METERS_PER_INCH = 0.0254; Scanner in = new Scanner(System.in); System.out.print("Please enter a measurement in meters: "); double meters = in.nextDouble(); System.out.println("Coverted to miles: " + meters / METERS_PER_MILE); System.out.println("Coverted to feet: " + meters / METERS_PER_FEET); System.out.println("Coverted to inches: " + meters / METERS_PER_INCH); } }
Write a program that translates a letter grade into a number grade. Letter grades are A, B, C, D, and F, possibly followed by + or -. Their numeric values are 4, 3, 2, 1, and 0. There is no F+ or F-. A + increases the numeric value by 0.3, a - decreases it by 0.3. However, an A+ has value 4.0.
import java.util.Scanner; public class LetterGradeToNumber { public static void main(String[] args) { Scanner in = new Scanner(System.in); final double A_VALUE = 4.0; final double B_VALUE = 3.0; final double C_VALUE = 2.0; final double D_VALUE = 1.0; final double F_VALUE = 0.0; final double PLUS_OR_MINUS_ADJUSTMENT = 0.3; System.out.println("Enter letter grade: "); String grade = in.next(); double numericValue = F_VALUE; if (grade.charAt(0) == 'A') { numericValue = A_VALUE; } if (grade.charAt(0) == 'B') { numericValue = B_VALUE; } if (grade.charAt(0) == 'C') { numericValue = C_VALUE; } if (grade.charAt(0) == 'D') { numericValue = D_VALUE; } if (grade.charAt(0) == 'F') { numericValue = F_VALUE; } if (grade.length() == 2) { // has a + or - if (grade.charAt(1) == '+') { if (grade.charAt(0) != 'A') { numericValue += PLUS_OR_MINUS_ADJUSTMENT; } } else { // It must be a '-' numericValue -= PLUS_OR_MINUS_ADJUSTMENT; } } System.out.printf("The numeric value is %.1f.", numericValue); } }
Write a program that reads a temperature value and the letter C for Celsius or F for Fahrenheit. Print whether water is liquid, solid, or gaseous at the given temperature at sea level.
import java.util.Scanner; public class MatterState { public static void main(String[] args) { final double GAS_STATE_CELSIUS = 100; final double LIQUID_STATE_CELSIUS = 0; final double GAS_STATE_FAHRENHEIT = 212; final double LIQUID_STATE_FAHRENHEIT = 32; Scanner in = new Scanner(System.in); System.out.println("Enter temperature: "); double temp = in.nextDouble(); System.out.println("Enter C for Celsius or F for Fahrenheit:"); String type = in.next(); if (type.compareTo("C") == 0) { // Celsius if (temp > GAS_STATE_CELSIUS) { System.out.println("It's a gas."); } else if (temp > LIQUID_STATE_CELSIUS) { System.out.println("It's a liquid."); } else { System.out.println("It's a solid."); } } else { // Fahrenheit if (temp > GAS_STATE_FAHRENHEIT) { System.out.println("It's a gas."); } else if (temp > LIQUID_STATE_FAHRENHEIT) { System.out.println("It's a liquid."); } else { System.out.println("It's a solid."); } } } }
The boiling point of water drops by about one degree centigrade for every 300 meters (or 1,000 feet) of altitude. Improve the program of Exercise R3.9 to allow the user to supply the altitude in meters or feet.
import java.util.Scanner; public class MatterState { public static void main(String[] args) { final double GAS_STATE_CELSIUS = 100; final double LIQUID_STATE_CELSIUS = 0; final double GAS_STATE_FAHRENHEIT = 212; final double LIQUID_STATE_FAHRENHEIT = 32; final double BOILING_POINT_DROP_CELSIUS_FEET = 1000; final double BOILING_POINT_DROP_CELSIUS_METERS = 300; final double BOILING_POINT_DROP_FAHRENHEIT_FEET = 5.0 / 9.0 * BOILING_POINT_DROP_CELSIUS_FEET; final double BOILING_POINT_DROP_FAHRENHEIT_METERS = 5.0 / 9.0 * BOILING_POINT_DROP_CELSIUS_METERS; Scanner in = new Scanner(System.in); System.out.println("Enter temperature: "); double temp = in.nextDouble(); System.out.println("Enter C for Celsius or F for Fahrenheit:"); String type = in.next(); System.out.println("Enter elevation: "); double elevation = in.nextDouble(); System.out.println("Enter M for meters or F for feet: "); String elevationUnits = in.next(); if (type.compareTo("C") == 0) { double boilingPoint = GAS_STATE_CELSIUS; if (elevationUnits.compareTo("F") == 0) { boilingPoint -= BOILING_POINT_DROP_CELSIUS_FEET * elevation; } else { boilingPoint -= BOILING_POINT_DROP_CELSIUS_METERS * elevation; } // Celsius if (temp > boilingPoint) { System.out.println("It's a gas."); } else if (temp > LIQUID_STATE_CELSIUS) { System.out.println("It's a liquid."); } else { System.out.println("It's a solid."); } } else { double boilingPoint = GAS_STATE_FAHRENHEIT; if (elevationUnits.compareTo("F") == 0) { boilingPoint -= BOILING_POINT_DROP_FAHRENHEIT_FEET * elevation; } else { boilingPoint -= BOILING_POINT_DROP_FAHRENHEIT_METERS * elevation; } // Fahrenheit if (temp > boilingPoint) { System.out.println("It's a gas."); } else if (temp > LIQUID_STATE_FAHRENHEIT) { System.out.println("It's a liquid."); } else { System.out.println("It's a solid."); } } } }
Write a program that transforms numbers 1, 2, 3, ..., 12 into the corresponding month names January, February, March, ..., December. Hint: Make a very long string "January February March ...", in which you add spaces such that each month name has the same length. Then use substring to extract the month you want.
import java.util.Scanner; public class MonthNames { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a month number (1 through 12): "); int month = in.nextInt(); String monthNames = "January February March April May June" + " July August September October November December "; String monthAsText = monthNames.substring((month - 1) * 9, (month) * 9); System.out.println(monthAsText); } }
An online bank wants you to create a program that shows prospective customers how their deposits will grow. Your program should read the initial balance and the annual interest rate. Interest is compounded monthly. Print out the balances after the first three months.
import java.util.Scanner; public class MonthlyBalance { public static void main(String[] args) { Scanner in = new Scanner(System.in); // input of balance and rate System.out.print("Initial balance : "); double initAmt = in.nextDouble(); System.out.print("Annual interest rate in percent: "); double rate = in.nextDouble(); // formatted output initAmt = initAmt + initAmt * (rate /(100.0*12)); System.out.printf("After first month: %.2f\n ", initAmt); initAmt = initAmt + initAmt * (rate /(100.0*12)); System.out.printf("After second month: %.2f\n" , initAmt); initAmt = initAmt + initAmt * (rate /(100.0*12)); System.out.printf("After third month: %.2f\n" , initAmt); } }
Write a program that reads three numbers and prints "all the same" if they are all the same, "all different" if they are all different, and "neither" otherwise.
import java.util.Scanner; public class NumCompare { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter three numbers: "); double a = in.nextDouble(); double b = in.nextDouble(); double c = in.nextDouble(); if (a == b && b == c) { System.out.println("all the same"); } else if (a != b && b != c && c != a) { System.out.println("all different"); } else { System.out.println("neither"); } } }
Write a program that reads an integer and prints whether it is negative, zero, or positive.
import java.util.Scanner; public class NumberInt { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a number: "); int i = in.nextInt(); if (i < 0) { System.out.println("It's a negative number."); } else if (i == 0) { System.out.println("It's a zero."); } else { System.out.println("It's a positive number."); } } }
Write a program that reads a word and prints all substrings, sorted by length. For example, if the user provides the input "rum", the program prints
import java.util.Scanner; public class PrintAllSubstrings { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a word: "); String word = in.next(); for (int length = 1; length <= word.length(); length++) { // This loop boundary defines the last position we can reach without // going off the end of the string for (int pos = 0; pos <= word.length() - length; pos++) { System.out.println(word.substring(pos, pos + length)); } } } }
Write a program that prompts the user for two integers and then prints • The sum • The difference • The product • The average • The distance (absolute value of the difference) • The maximum (the larger of the two) • The minimum (the smaller of the two) Hint: The max and min functions are declared in the Math class.
import java.util.Scanner; public class PrintNumberStats { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter the first integer: "); int firstInt = in.nextInt(); System.out.print("Please enter the second integer: "); int secondInt = in.nextInt(); int sum = firstInt + secondInt; System.out.printf("Sum: %d\n", sum); int difference = firstInt - secondInt; System.out.printf("Difference: %d\n", difference); int product = firstInt * secondInt; System.out.printf("Product: %d\n", product); double average = (firstInt + secondInt) / 2.0; System.out.printf("Average: %f\n", average); int distance = Math.abs(difference); System.out.printf("Distance: %d\n", distance); int max = Math.max(firstInt, secondInt); System.out.printf("Maximum: %d\n", max); int min = Math.min(firstInt, secondInt); System.out.printf("Minimum: %d\n", min); } }
Write a program that prompts the user for a radius and then prints • The area and circumference of a circle with that radius • The volume and surface area of a sphere with that radius
import java.util.Scanner; public class RadiusCalculations { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a radius: "); double radius = in.nextDouble(); System.out.println("Area of circle:" + (Math.PI * Math.pow(radius, 2))); System.out.println("Circumference of circle: " + (2 * Math.PI * radius)); System.out.println("Volume of sphere: " + (4.0 / 3.0 * Math.PI * Math.pow(radius, 3))); System.out.println("Surface area of sphere: " + (4.0 * Math.PI * Math.pow(radius, 2))); } }
Write a program that reads a word and prints the word in reverse. For example, if the user provides the input "Harry", the program prints yrraH
import java.util.Scanner; public class ReverseWord { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a word: "); String word = in.next(); for (int i = word.length() - 1; i >= 0; i--) { System.out.print(word.charAt(i)); } } }
Write a program that reads a number and displays the square, cube, and fourth power. Use the Math.pow method only for the fourth power.
import java.util.Scanner; public class Powers { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a number: "); double number = in.nextDouble(); double square = number * number; System.out.printf("Square: %f\n", square); double cube = number * number * number; System.out.printf("Cube: %f\n", cube); double fourthPower = Math.pow(number, 4); System.out.printf("Fourth Power: %f\n", fourthPower); } }
Rewrite the following do loop into a while loop. int n = in.nextInt(); double x = 0; double s; do { s = 1.0 / (1 + n * n); n++; x = x + s; } while (s > 0.01);
int n = in.nextInt(); double x = 0; double s; s = 1.0 / (1 + n * n); n++; x = x + s; while (s > 0.01) { s = 1.0 / (1 + n * n); n++; x = x + s; }
Rewrite the following for loop into a while loop. int s = 0; for (int i = 1; i = 10; i++) { s = s + i; }
int s = 0; int i = 1; while (i <= 10) { s = s + i; i++; }
Each square on a chess board can be described by a letter and number, such as g5 in this example: The following pseudocode describes an algorithm that determines whether a square with a given letter and number is dark (black) or light (white). If the letter is an a, c, e, or g If the number is odd color = "black" Else color = "white" Else If the number is even color = "black" Else color = "white" Using the procedure in Programming Tip 3.5, trace this pseudocode with input g5.
letter number color 9 5 "black"
rite a program that displays the dimensions of a letter-size (8.5 × 11 inches) sheet of paper in millimeters. There are 25.4 millimeters per inch. Use constants and comments in your program.
public class LetterDim { public static void main(String[] args) { // Define a constant for the conversion to metric final double INCHES_TO_MILLIMETERS = 25.4; // Define constants for paper size in inches final double PAPER_WIDTH_IN = 8.5; final double PAPER_LENGTH_IN = 11.0; // Define variables for millimeters and convert double paperWidthmm = PAPER_WIDTH_IN * INCHES_TO_MILLIMETERS; double paperLengthmm = PAPER_LENGTH_IN * INCHES_TO_MILLIMETERS; // Display (print to screen) the dimensions in mm System.out.println("The metric dimensions of a letter-sized sheet of paper are " + paperWidthmm+ " mm by " + paperLengthmm + " mm."); } }
Printing a grid. Write a program that prints the following grid to play tic-tac-toe. Of course, you could simply write seven statements of the form System.out.println("+--+--+--+"); You should do it the smart way, though. Declare string variables to hold two kinds of patterns: a comb-shaped pattern and the bottom line. Print the comb three times and the bottom line once.
public class PrintGrid { public static void main(String[] args) { String bottomLine = "+--+--+--+"; String combPattern = "+--+--+--+\n| | | |"; System.out.println(combPattern); System.out.println(combPattern); System.out.println(combPattern); System.out.println(bottomLine); } }
Classify program errors as compile-time and run-time errors.
A compile-time error is a violation of the programming language rules that is detected by the compiler. A run-time error causes a program to take an action that the programmer did not intend.
What is required to play music on a computer?
A program that reads the data on the CD and sends output to the speakers and the screen.
What does a computer user need to know about programming in order to play a video game?
Nothing.
Write a method public static int countVowels(String str) that returns a count of all vowels in the string str. Vowels are the letters a, e, i, o, and u, and their uppercase variants.
/** Count the number of vowels in a given string. @param str string to count vowels in @return number of vowels in str */ public static int countVowels(String str) { int count = 0; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') { count++; } } return count; }
Variable Names
1. Variable names must start with a letter or the underscore (_) character, and the remaining characters must be letters, numbers, or underscores. (Technically, the $ symbol is allowed as well, but you should not use it—it is intended for names that are automatically generated by tools.) 2. You cannot use other symbols such as ? or %. Spaces are not permitted inside names either. You can use uppercase letters to denote word boundaries, as in cansPerPack. This naming convention is called camel case because the uppercase letters in the middle of the name look like the humps of a camel.) image © GlobalP/iStockphoto 3. Variable names are case sensitive, that is, canVolume and canvolume are different names. 4. You cannot use reserved words such as double or class as names; these words are reserved exclusively for their special Java meanings. (See Appendix C for a listing of all reserved words in Java.)
What is an infinite loop? On your computer, how can you terminate a program that executes an infinite loop?
An infinite loop occurs when the terminating condition in the loop never evaluates to false. How you stop an infinite loop on your computer depends on your operating system and your IDE. For example, in the Eclipse IDE there is a red "TERMINATE" button that will stop any Java program at any time.
The "advanced search" feature of many search engines allows you to use Boolean operators for complex queries, such as "(cats OR dogs) AND NOT pets". Contrast these search operators with the Boolean operators in Java.
Boolean operations in search engines are spelled out in English while in Java they have symbolic replacements. For example OR is equivalent to "||" in Java while AND NOT could be equivalent to "!=".
How do you modify the HelloPrinter program to greet you instead?
Change World to your name (here, Dave): System.out.println("Hello, Dave!");
Describe the building blocks of a simple program.
Classes are the fundamental building blocks of Java programs. Every Java application contains a class with a main method. When the application starts, the instructions in the main method are executed. Each class contains declarations of methods. Each method contains a sequence of instructions. A method is called by specifying the method and its arguments. ring is a sequence of characters enclosed in quotation marks.
Constants
Constants are commonly written using capital letters to distinguish them visually from regular variables: final double BOTTLE_VOLUME = 2;
What do the following statements print? System.out.println("Hello"); System.out.println(""); System.out.println("World");
Hello a blank line World
What does this program print? Pay close attention to spaces. public class Test { public static void main(String[] args) { System.out.print("Hello"); System.out.println("World"); } }
HelloWorld Because there are no spaces after the System.out.print("Hello"); the next line prints World directly after Hello is printed.
Where is a program stored when it is not currently running?
In secondary storage, typically a hard disk.
Explain the difference between an if/else if/else sequence and nested if statements. Give an example of each.
In the case of an if/else if/else sequence, one clause is guaranteed to be executed, while in the case of nested if statements the internal clause is only true if all the if statements are true. As an example one of the following lines of code will be printed: if (n > 10) { System.out.println("Greater than 10!"); } else if (n >= 0) { System.out.println("Between 0 and 10."); } else { System.out.println("Less than 0.") Whereas in this case the print will only execute if n is both greater than or equal to 0 and less than or equal to 10: if (n >= 0) { if (n <= 10) { System.out.println("Between 0 and 10."); } }
What is the compile-time error in this program? public class Test { public static void main(String[] args) { System.out.println("Hello", "World!"); } }
Java interprets the comma in the println method to mean that two strings are passed to println. It's likely the programmer meant to do this: System.out.print("Hello, World!");
Would the program continue to work if you replaced line 5 with this statement? System.out.println(Hello);
No. The compiler would look for an item whose name is Hello. You need to enclose Hello in quotation marks: System.out.println("Hello");
Write pseudocode for simple algorithms.
Pseudocode is an informal description of a sequence of steps for solving a problem. An algorithm for solving a problem is a sequence of steps that is unambiguous, executable, and terminating.
Write a program that prints a greeting of your choice, perhaps in a language other than English.
Public class Greeting { public static void main(String[] args) { System.out.println("Romanian greeting: Salut! Ce face?"); } }
Write pseudocode for a program that reads a name (such as Harold James Morgan) and then prints a monogram consisting of the initial letters of the first, middle, and last name (such as HJM).
Read first name into variable called first. Read middle name into variable called middle. Read last name into variable called last. Print first character in first. Print first character in middle. Print first character in last.
Write pseudocode for a program that reads a word and then prints the first character, the last character, and the characters in the middle. For example, if the input is Harry, the program prints H y arr.
Read input into a variable called word. Print first character in word followed by a space. Print character at length -1 in word followed by a space. Print substring between 1st and last character (length -1) in word.
What are the two most important benefits of the Java language?
Safety and portability. Other benefit: The same Java program will run, without change, on Windows, UNIX, Linux, or Macintosh.
How would you modify the HelloPrinter program to print the word "Hello" vertically?
System.out.println("H"); System.out.println("e"); System.out.println("l"); System.out.println("l"); System.out.println("o");
Where is the HelloPrinter.java file stored on your computer?
The answer varies among systems. A typical answer might be /home/dave/cs1/hello/HelloPrinter.java or c:\Users\Dave\Workspace\hello\HelloPrinter.java
Describe the components of a computer.
The central processing unit (CPU) performs program control and data processing. Storage devices include memory and secondary storage.
Which part of the computer carries out arithmetic operations, such as addition and multiplication?
The central processing unit.
True or false? A && B is the same as B && A for any Boolean conditions A and B.
This is true, the Boolean operation && is symmetric. One can test this by filling in all values of a truth table and noting both operations A && B and B && A have the same truth values: A B A && B B && A false false false false false true false false true false false false true true true true
Write a program that prints the values 3 * 1000 * 1000 * 1000 3.0 * 1000 * 1000 * 1000
This program: public class R222 { public static void main(String[] args) { System.out.println(3 * 1000 * 1000 * 1000); System.out.println(3.0 * 1000 * 1000 * 1000); } } Prints out the following: -1294967296 3.0E9 The reason the first number is negative is because we have exceeded the limited range of an int and the number overflowed to a negative. The second number's result is correct but displayed in scientific notation because it is a floating-point type from the 3.0 in the calculation.
Escape Sequences The sequence \" is called an escape sequence. Another common escape sequence is \n, which denotes a newline character
To include a quotation mark in a literal string, precede it with a backslash (\), like this: "He said \"Hello\"" The backslash is not included in the string. It indicates that the quotation mark that follows should be a part of the string and not mark the end of the string. To include a backslash in a string, use the escape sequence \\, like this: "C:\\Temp\\Secret.txt" Another common escape sequence is \n, which denotes a newline character. Printing a newline character causes the start of a new line on the display. For example, the statement System.out.print("*\n**\n***\n"); prints the characters * ** *** on three separate lines. You often want to add a newline character to the end of the format string when you use System.out.printf: System.out.printf("Price: %10.2f\n", price);
String Input You can read a string from the console: System.out.print("Please enter your name: "); String name = in.next();
When a string is read with the next method, only one word is read. For example, suppose the user types Harry Morgan as the response to the prompt. This input consists of two words. The call in.next() yields the string "Harry". You can use another call to in.next() to read the second word.
Give a set of four test cases for the algorithm of Exercise R3.9 that covers all branches.
The following test cases cover all four branches. a) "g5" b) "h5" c) "g4" d) "h4"
Consider the following code segment. double purchase = 19.93; double payment = 20.00; double change = payment - purchase; System.out.println(change); The code segment prints the change as 0.07000000000000028. Explain why. Give a recommendation to improve the code so that users will not be confused.
The given output is printed in a raw format up to the range of a double data type. Users can use format specifiers (printf with %) to format the output as they require.
What does the following set of statements print? System.out.print("My lucky number is"); System.out.println(3 + 4 + 5);
The printout is My lucky number is12. It would be a good idea to add a space after the is.
Which parts of a computer can store program code? Which can store user data?
Typically program code is stored on a hard disk, CD/DVD disc, or in some other central location across a network. User data is often more likely to be stored on a local hard disk, although it can also be stored on a network or even a CD/DVD for backup storage.
Give an example of an if/else if/else sequence where the order of the tests does not matter. Give an example where the order of the tests matters.
When comparing exact values the order of if/else if/else statements does not matter: if (n == 1) { System.out.println("1."); } else if (n == 2) { System.out.println("2."); } else { System.out.println("Something else."); } When comparing ranges of values it can: if (n > 10) { System.out.println("Greater than 10!"); } else if (n >= 0) { System.out.println("Between 0 and 10."); } else { System.out.println("Less than 0."); }
Write a program that prints the product of the first ten positive integers, 1 × 2 × ... × 10. (Use * to indicate multiplication in Java.)
public class PrintProduct { public static void main(String[] args) { System.out.println(1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10); } }
What do you do to protect yourself from data loss when you work on programming projects?
You back up your files and folders.
Comments
You use the // delimiter for short comments. If you have a longer comment, enclose it between /* and */ delimiters. The compiler ignores these delimiters and everything in between.
Explain what each of the following program segments computes. a) x = 2; y = x + x; b) s = "2"; t = s + s;
a) This statement doubles the value of x. Given the initial value of x as 2, the result is 4. b) This statement concatenates the strings "2" together. The result is "22".